我将如何转换这样的字符串 "13.2..2"
到这样的列表[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
我看过digitToInt
但它不照顾Maybe Int
.有什么办法可以修改digitToInt
办理Maybe Int
?
最佳答案
您可以使用 isDigit
测试是否digitToInt
将会成功。
λ> fmap (\c -> if isDigit c then Just (digitToInt c) else Nothing) "13.2..2" :: [Maybe Int]
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
我们可以引入一个新函数来稍微清理一下:
digitToIntMay :: Char -> Maybe Int
digitToIntMay c = if isDigit c then Just (digitToInt c) else Nothing
λ> fmap digitToIntMay "13.2..2" :: [Maybe Int]
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
关于haskell - 如何将字符串转换为 Maybe Int 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960597/