当我在整数列表上“读取”时如何捕获错误?

时间:2011-06-09 06:57:08

标签: haskell

我需要帮助,我必须阅读类似["1", "2", "3"]的列表,并列出整数[1,2,3],因此我使用read

问题是,当列表看起来像["1", "2", "a"]时,程序因为其中有一个字符的错误而退出。

如何检查或抛出错误以防止此错误?

1 个答案:

答案 0 :(得分:6)

您应该使用reads,而不是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>