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

前端 未结 4 1178
生来不讨喜
生来不讨喜 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:12

    Here's an improved maybeRead which allows only for trailing whitespaces, but nothing else:

    import Data.Maybe
    import Data.Char
    
    maybeRead2 :: Read a => String -> Maybe a
    maybeRead2 = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads
    

提交回复
热议问题