[Haskell-cafe] Safe way to parse arguments?

Dan Doel dan.doel at gmail.com
Sat Jun 21 17:37:24 EDT 2008


On Saturday 21 June 2008, Don Stewart wrote:
>       maybeRead :: Read a => String -> Maybe a
>       maybeRead s = case reads s of
>           [(x, "")] -> Just x
>           _         -> Nothing

Note, if you want to match the behavior of read, you'll probably want 
something like:

    maybeRead :: Read a => String -> Maybe a
    maybeRead s = case reads s of
        [(x, str)] | all isSpace str -> Just x
        _                            -> Nothing

Otherwise, trailing spaces will yield a bad parse.

-- Dan


More information about the Haskell-Cafe mailing list