missingfaktor
missingfaktor

Reputation: 92026

Catching errors thrown with `error`?

There are some stdlib functions that throw errors on invalid input. For example:

Prelude> read "1o2" :: Int
*** Exception: Prelude.read: no parse

I would like to wrap it to return a Either e a instead. How can I do that?

Upvotes: 9

Views: 201

Answers (2)

Don Stewart
Don Stewart

Reputation: 137947

I prefer to turn errors into values:

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

Upvotes: 2

Daniel Wagner
Daniel Wagner

Reputation: 152707

There is no spoon. You didn't hear it from me.

For this particular example, though, you should use reads instead.

Upvotes: 14

Related Questions