开发者

howto catch a error when i do "read" on a list of integer?

i need help, i have to read a list like this ["1", "2", "3"] and make a list of integer of it [1,2,3] so i use read.

the problem is, when the li开发者_开发知识库st looks like ["1", "2", "a"] the programm quits because of the error that there is a char in it.

how to check or throw an error to prevent this error?


You should be using reads, not read.

Prelude> :m Data.Maybe
Prelude Data.Maybe> (map (fmap fst . listToMaybe . reads) ["1", "2", "3"]) :: [Maybe Integer]
[Just 1,Just 2,Just 3]
Prelude Data.Maybe> (map (fmap fst . listToMaybe . reads) ["1", "2", "a"]) :: [Maybe Integer]
[Just 1,Just 2,Nothing]
Prelude Data.Maybe> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜