Skip to content

Instantly share code, notes, and snippets.

@joseph-montanez
Created July 30, 2011 20:52
Show Gist options
  • Save joseph-montanez/1115980 to your computer and use it in GitHub Desktop.
Save joseph-montanez/1115980 to your computer and use it in GitHub Desktop.
Learning me a Haskell
{-|
The 'toDouble' will take a string and force it to a Double. On failure the
it will just return 0.00
-}
toDouble :: String -> Double
toDouble x = do
-- try to convert a String to a decimal number, if not fall back to a string,
-- this will prevent haskell from erroring out
case reads x :: [(Double, String)] of
-- if there is a match for any decimal number and an empty string
y@[(_, "")] -> -- The y@ just references the pattern to be used below
-- grap the first tuple (there is only ever one),
-- then grap the first item from the tuple
fst (head y)
-- any matches for anything else will just return 0.00
_ -> 0.00 -- default to 0.00 on failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment