0

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?

Avada Kedavra
  • 8,523
  • 5
  • 32
  • 48
el diablo
  • 2,647
  • 2
  • 20
  • 22

2 Answers2

1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Very clever. I actually figured out how to reverse the digits of the number mathematically using mod and div and so no longer need to convert the numbers to a list in order to Reverse them. Thanks. – el diablo Sep 27 '09 at 12:03
1

This should do the trick more succintly:

{Show {StringToInt {Reverse {IntToString 123}}}}

Cheers

JFT
  • 827
  • 8
  • 6