Big Numbers: Input And Output

June 14, 2011

We continue our series on implementing a big number library by writing the functions that translate between strings and big numbers. You may recall that we cheated in the first big number exercise by using the native big numbers of Scheme to provide input and output. In today’s exercise we overcome that cheating by writing our own functions.

The two functions that convert between strings and big numbers both take an optional argument that represents the radix in which the strings are represented, which can range from 2 to 36 inclusive; if no radix is given, it defaults to 10. The functions are similar to the digits and undigits functions of the Standard Prelude.

Your task is to write the two functions that convert between big numbers and strings. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

About these ads

Pages: 1 2 3

One Response to “Big Numbers: Input And Output”

  1. My Haskell solution (see for a version with comments):

    readBase :: (Num a, Enum a) => a -> String -> a
    readBase b ('-':xs) = - readBase b xs
    readBase b xs       = foldl (\a x -> b * a + val x) 0 xs where
        val d = maybe (error "unrecognized digit") id . lookup d $ zip
                (['0'..'9'] ++ ['A'..'Z'] ++ ['a'..'z']) [0..]
    showBase :: Integral a => a -> a -> String
    showBase b n = if n < 0 then '-' : showBase b (abs n) else
                   map (digit . snd) $ m : reverse ms  where
        ((_:ms), (m:_)) = span ((> 0) . fst) $ iterate (flip divMod b . fst) (n, 0)
        digit d = maybe undefined id . lookup d . zip [0..] $
                  ['0'..'9'] ++ ['A'..'Z'] ++ ['a'..'z']

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 574 other followers

%d bloggers like this: