Skip to content

Instantly share code, notes, and snippets.

@tafsiri
Created February 26, 2012 07:24
Show Gist options
  • Save tafsiri/1914705 to your computer and use it in GitHub Desktop.
Save tafsiri/1914705 to your computer and use it in GitHub Desktop.
-- Q3 Write a function that converts a string to a numerical type. The string is in the form
-- $2,345,678.99 and can have leading zeroes.
-- I'm not going to be doing error checking on the format btw
strToNum :: Fractional a => [Char] -> a
strToNum str = let
-- remove the '$' and ','
plain = filter (\x -> x /= '$' && x /= ',') str
whole = takeWhile (\x -> x /= '.') plain
fractional = tail (dropWhile (\x -> x /= '.') plain)
in (strToNumWhole whole) + (strToNumFrac fractional)
-- helper functions
strToNumWhole :: Num a => [Char] -> a
strToNumWhole str = let
-- use a zip to combine the individual chars with the index of their position
-- we will use the index to multiply 10s, 100s, 1000s, etc
-- produces a list of tuples like [("2", 0), ("1"), 1] from the string "12"
withIndices = zip (reverse str) [0..]
in sum (map (\pair -> (digitToNum (fst pair)) * (10 ^ snd pair)) withIndices)
strToNumFrac :: Fractional a => [Char] -> a
strToNumFrac str = let
withIndices = zip (str) [1..]
in sum (map (\pair -> (digitToNum (fst pair)) / (10 ^ snd pair)) withIndices)
digitToNum :: Num a => Char -> a
digitToNum '0' = 0
digitToNum '1' = 1
digitToNum '2' = 2
digitToNum '3' = 3
digitToNum '4' = 4
digitToNum '5' = 5
digitToNum '6' = 6
digitToNum '7' = 7
digitToNum '8' = 8
digitToNum '9' = 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment