Search code examples
ozmozart

How do I convert an integer to a list and vice versa in Oz?


How do I convert an integer to a list and back in Oz? I need to take a number like 321 and reverse it into 123.

The Reverse function in Oz only works on lists so I want to convert 321 to [3 2 1], reverse it, and convert [1 2 3] back to 123. Can this be done in Oz?


Solution

  • Disclaimer: I didn't actually know Oz until 5 minutes ago and only read the examples at Wikipedia, so the following may be riddled with errors. It should however give you a good idea on how to approach the problem. (Making the function tail-recursive is left as an exercise to the reader).

    Update: The following version is tested and works.

    local
      % turns 123 into [3,2,1]
      fun {Listify N}
        if N == 0 then nil
        else (N mod 10) | {Listify (N div 10)}
        end
      end
    
      % turns [1,2,3] into 321
      fun {Unlistify L}
        case
          L of nil then 0
          [] H|T then H + 10 * {Unlistify T}
        end
      end
    in
      % Turns 123 into 321
      {Browse {Unlistify {Reverse {Listify 123}}}}
    end