[Haskell-cafe] swap a pair of integers

Tim Toorop timtoorop at quicknet.nl
Mon May 29 17:31:21 EDT 2006


David House wrote:
>
> When you want to do manipulation on the digits of a number like this,
> normally the easiest thing to do is to convert it to a string, use
> list manipulation functions, then convert back to an integer.
>
> For example:
>
> Prelude> (read . reverse . show) 17
> 71
swapInteger :: Integer -> Integer
swapInteger x = swapInteger' (x,0)


swapInteger' :: (Integer,Integer) -> Integer
swapInteger' (0,x) = x
swapInteger' (remaining, result) =  swapInteger' $ (remaining', 
result*10 + result')
        where (remaining', result') = remaining `divMod` 10


Works for all positive integer, and doesn't hassle around with 
converting it to a string.


More information about the Haskell-Cafe mailing list