如何将字符串转换为Maybe Int列表

时间:2017-05-14 05:10:01

标签: haskell

我如何将像"13.2..2"这样的字符串转换为像这样的列表

[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]

我查看了digitToInt,但它没有处理Maybe Int。有没有办法可以修改digitToInt来处理Maybe Int

3 个答案:

答案 0 :(得分:7)

您可以使用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]

答案 1 :(得分:5)

如果您希望将所有非数字转换为Nothing,则可以使用警卫和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更加惯用。

答案 2 :(得分:1)

如果您确定所发送的数据肯定是数字或plot(1, ty = 'n') a = .234; b = -.335 if (b > 0) { legend("center", legend = bquote(bold(Outcome[i] == .(round (a , 2))~ + ~. (round(b , 2))~"\u00D7"~Predictor[i])), bty = "n") } else { legend("center", legend = bquote(bold(Outcome[i] == .(round (a , 2))~ . (round(b , 2))~"\u00D7"~Predictor[i])), bty = "n") } (或者如果数据不同则对引发的异常感到满意),则可以使用模式匹配和. < / p>

fmap