How to catch a no parse exception from the read function in Haskell?

前端 未结 4 1180
生来不讨喜
生来不讨喜 2020-12-05 10:18

In my Haskell program, I want to read in a value given by the user using the getLine function. I then want to use the read function to convert thi

4条回答
  •  一生所求
    2020-12-05 11:14

    You don't want to. You want to use reads instead, possibly like that:

    maybeRead = fmap fst . listToMaybe . reads
    

    (though you might want to error out if the second element of the tuple is not "", that is, if there's a remaining string, too)

    The reason why you want to use reads instead of catching error exceptions is that exceptions in pure code are evil, because it's very easy to attempt to catch them in the wrong place: Note that they only fly when they are forced, not before. Locating where that is can be a non-trivial exercise. That's (one of the reasons) why Haskell programmers like to keep their code total, that is, terminating and exception-free.

    You might want to have a look at a proper parsing framework (e.g. parsec) and haskeline, too.

提交回复
热议问题