9

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?

missingfaktor
  • 90,905
  • 62
  • 285
  • 365

2 Answers2

14

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

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

Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
2

I prefer to turn errors into values:

 maybeRead :: Read a => String -> Maybe a
 maybeRead s = case reads s of
      [(x, "")] -> Just x
      _         -> Nothing
Don Stewart
  • 137,316
  • 36
  • 365
  • 468
  • I too prefer that, but the question is about doing it _generally_. `read` is used only as an example. – missingfaktor Jun 07 '12 at 12:15
  • I think it is generally true that, for any function which throws an error, there will be a "safe" version of it. – Tyler Jun 07 '12 at 16:05