我怎么会去有关转换的字符串这样"13.2..2"
到列表这样如何将字符串转换为的也许诠释
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
名单我已经在digitToInt
一看,但它确实没有照顾Maybe Int
。有没有办法我可以修改digitToInt
来处理Maybe Int
?
我怎么会去有关转换的字符串这样"13.2..2"
到列表这样如何将字符串转换为的也许诠释
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
名单我已经在digitToInt
一看,但它确实没有照顾Maybe Int
。有没有办法我可以修改digitToInt
来处理Maybe Int
?
如果希望所有非数字转换为Nothing
,则CA氮利用警卫和fmap
import Data.Char
charToMaybeInt :: Char -> Maybe Int
charToMaybeInt x
| isDigit x = Just $ digitToInt x
| otherwise = Nothing
main = putStrLn $ show $ fmap charToMaybeInt "13.2..2"
使用卫士是,从我的非专业的认识,有点比使用if
/else
更地道。
您可以使用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]
如果你是某个数据来绝对是一个数字或.
(或者是高兴异常被抛出,如果的数据是不同的),可以使用模式匹配和fmap
import Data.Char
chatToMaybeInt :: Char -> Maybe Int
chatToMaybeInt '.' = Nothing
chatToMaybeInt x = Just $ digitToInt x
main = putStrLn $ show $ fmap chatToMaybeInt "13.2..2"
两个答案?!?为什么不把这两个合并为一个呢? –
@StephaneRolland因为它们不同:它们使用不同的代码,语言特征并具有不同的优点/缺点。例如,这个可以抛出异常,OP /选民可能找不到合适的例外。从我可以告诉,多个答案可以接受https://meta.stackexchange.com/questions/25209/what-is-the-official-etiquette-on-answering-a-question-twice。 –
为什么所有的关闭/低票?这绝对不是“太宽泛”,很清楚要问什么。 –