[Haskell-beginners] using "read"

Rahul Kapoor rk at trie.org
Fri Jan 15 14:18:43 EST 2010

> An absolute beginner as i am, want to use "read" to convert a String in a Int, but I don't know how to protect my ? > >function func from an exception when str is not a number like "12A". How can I do?

Try reads instead. Something like

readMaybe s = case reads s of
              [(i,"")] -> Just i
              _        -> Nothing

Returns "Just" the value parsed in case all input is consumed and
Nothing otherwise.
A similar version can be made if partial parses are acceptable.


More information about the Beginners mailing list