我如何将像"13.2..2"
这样的字符串转换为像这样的列表
[Just 1, Just 3, Nothing, Just 2, Nothing, Nothing, Just 2]
我查看了digitToInt
,但它没有处理Maybe Int
。有没有办法可以修改digitToInt
来处理Maybe Int
?
答案 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