[Haskell-cafe] handling read exceptions

S. Alexander Jacobson alex at alexjacobson.com
Mon Apr 12 13:58:01 EDT 2004


My point is that I am reading in name/value pairs
and once I know the name, I know the type of the
value, but I don't want to have to pass that
information programatically to the point in the
code where I am doing the read.

-Alex-

On Mon, 12 Apr 2004, Sven Panne wrote:

> 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.
>

_________________________________________________________________
S. Alexander Jacobson                  mailto:me at alexjacobson.com
tel:917-770-6565                       http://alexjacobson.com


More information about the Haskell-Cafe mailing list