有一些stdlib函数会在无效输入时抛出错误。例如: Prelude> read "1o2" :: Int *** Exception: Prelude.read: no parse 我希望将其封装并返回 Either e a。我该怎么做?
我更喜欢将错误转化为值: maybeRead :: Read a => String -> Maybe a maybeRead s = case reads s of [(x, "")] -> Just x _ -> Nothing