[Haskell-cafe] handling read exceptions

Sven Panne Sven.Panne at aedion.de
Tue Apr 13 09:54:35 EDT 2004


S. Alexander Jacobson wrote:
> 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.

OK, I see... I don't know the exact syntax you are using (e.g. how
are the strings terminated?), but "reads" is still useful:

    readIS :: ReadS (Either Integer String)
    readIS s = take 1 $
               [ (Left  x, t) | (x, t) <- reads s ] ++
               [ (Right x, t) | (x, t) <- lex   s ]

Then we have:

    Main> readIS "123blah"
    [(Left 123,"blah")]
    Main> readIS "blah123"
    [(Right "blah123","")]
    Main> readIS ""
    [(Right "","")]
    Main> readIS "foo bar"
    [(Right "foo"," bar")]

If you have only simple parsing tasks and are not looking for extreme
performance, the Read class is a good choice. Otherwise you should
probably have a look at the Parsec package which comes with Hugs and GHC:

    http://www.haskell.org/ghc/docs/latest/html/libraries/parsec/Text.ParserCombinators.Parsec.html

or Happy:

    http://haskell.org/happy/

Cheers,
    S.



More information about the Haskell-Cafe mailing list