[Haskell-cafe] handling read exceptions

Sven Panne Sven.Panne at aedion.de
Mon Apr 12 19:42:51 EDT 2004


S. Alexander Jacobson wrote:
> I want to read strings that look like "2"  or
> "hello" into values of type Integer or String.
> The problem is that read requires that strings be
> read as "\"hello\"".  Is there a way either to
> convince read to not require wrapping quotation
> marks or, alternetively, to catch a read
> exception, and do something sane?

"reads" is probably what you are looking for:

    Prelude> (reads :: ReadS Integer) ""
    []
    Prelude> (reads :: ReadS Integer) "a"
    []
    Prelude> (reads :: ReadS Integer) "2"
    [(2,"")]
    Prelude> (reads :: ReadS Integer) "123blah"
    [(123,"blah")]

And reading a string the way you want is best done by "id". :-)

Cheers,
    S.



More information about the Haskell-Cafe mailing list