Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Created August 5, 2012 09:15
Show Gist options
  • Select an option

  • Save disolovyov/3263156 to your computer and use it in GitHub Desktop.

Select an option

Save disolovyov/3263156 to your computer and use it in GitHub Desktop.
Read from strings with a fallback on error
{-# LANGUAGE ScopedTypeVariables #-}
fromStr :: Read a => a -> String -> a
fromStr fallback s =
let parsed = reads s :: Read a => [(a, String)]
in case parsed of
[(result, _)] -> result
_ -> fallback
p :: Show a => a -> IO ()
p = putStrLn . show
main = do
p $ fromStr 0 "100"
p $ fromStr 0.0 "100"
p $ fromStr 0 "10x"
p $ fromStr 0 "xxx"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment