[Haskell-cafe] How to read safely?

Dan Doel dan.doel at gmail.com
Wed Jun 24 05:56:17 EDT 2009

On Wednesday 24 June 2009 5:40:28 am Magicloud Magiclouds wrote:
> Hi,
>   Read often throws runtime errors, which breaks the robust of the
> problem. How to deal with it? Without lost too much proformance (so
> reads is a no).
>   At least, if its error could be catched, that'd be better.

There was talk of adding a readMaybe a while ago, but apparently it never 

As it is, you can use reads, "read s" becomes:

    case reads s of
      [(a, rest)] | all isSpace rest -> <code using a>
      _                              -> <error case>

which ensures that you have an unambiguous parse with only trailing 
whitespace. You can, of course, modify that if you don't care about ambiguity 
or trailing characters.

Also, technically, if you're reading things in conjunction with IO code, you 
can use readIO, which throws a catchable IO exception on failure. But that 
obviously doesn't work in the general case.

-- Dan

More information about the Haskell-Cafe mailing list