Search code examples
haskellintegerint

How to reverse an integer in haskell?


I need help on how to reverse a Integer in Haskell with the following type signature:

reverseInt :: Integer -> Integer
reverseInt a = undefined -- help here

I need the Integer input number to be reversed like the example below.

Example:

> reverseInt 1989
9891

Solution

  • Convert the number to a string, revert that, then convert the reversed string back to a number. Integer values can be negative, so take care of a leading -:

    reverseInt :: Integer -> Integer
    reverseInt x | x < 0     = 0 - (read . reverse . tail . show $ x)
                 | otherwise = read . reverse . show $ x