Created
August 5, 2012 09:15
-
-
Save disolovyov/3263156 to your computer and use it in GitHub Desktop.
Read from strings with a fallback on error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# 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