Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
missingfaktor Avatar asked Jun 07 '12 06:06

missingfaktor


2 Answers

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

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

like image 61
Daniel Wagner Avatar answered Sep 22 '22 23:09

Daniel Wagner


I prefer to turn errors into values:

 maybeRead :: Read a => String -> Maybe a
 maybeRead s = case reads s of
      [(x, "")] -> Just x
      _         -> Nothing
like image 22
Don Stewart Avatar answered Sep 20 '22 23:09

Don Stewart