Search code examples
stringhaskellcharintegerdigits

How to convert Integer in String and String in Integer in Haskell?


I'm still learning Haskell and I'm really confused with this language... i have to implement two functions fromInteger :: Integer -> String and toInteger :: String -> Integer that translate between Haskell integers and numbers by strings of digits in reverse order, like: "25" -> "52". For the sake of functional decomposition i should first implement fromDigit :: Integer -> Char and toDigit :: Char -> Integer that translate between digits and characters. How should the function look like? Thanks a lot!


Solution

  • You can use read :: Read a => String -> a and show :: Show a => a -> String to convert from Integer and to a String:

    Prelude> show 52
    "52"
    Prelude> read "52" :: Integer
    52
    

    But you do not need to convert values to a string to reverse the order of the digits. You can use recursion and quotRem :: Integral a => a -> a -> (a, a) to obtain the quotient and remainder.

    You can also use recursing to convert an Integer to a String. Here we use as accumulator a String, and we each time calculate the last digit. This thus looks like:

    fromInteger :: Integer -> String
    fromInteger = go []
        where go ls x | x <= 9 = … : …
                      | otherwise = go (… : ls) …
                      where (q, r) = quotRem x 10

    where you still need to fill in the parts.