【发布时间】:2019-10-07 14:10:29
【问题描述】:
首先,我是 Haskell 的新手,所以如果我问的问题有点愚蠢,请告诉我如何才能做得更好。谢谢:)
我的任务是获取符合特定条件的字符串列表。如果没有字符串符合,我想评估为Nothing。所以我写了两个函数:
isSpecialLine :: String -> String -> Maybe Bool
isSpecialLine t s = Just $ (("[" ++ t ++ ":") `isPrefixOf` s) && ("]::" `isSuffixOf` s)
getLinesWith :: String -> String -> Maybe [String]
getLinesWith t = filterM (isSpecialLine t) . lines
这段代码有效,但我发现Maybe Bool 看起来有点奇怪。嘿,它是二进制的!它始终为True 或False,因此isSpecialLine 的值将始终为Just True 或Just False。就我而言,它永远不可能是Nothing!
但如果我将isSpecialLine 输出类型更改为Bool,则会出现以下问题:filterM 期望Maybe Bool 而不是Bool。
好的,我这样做:
getLinesWith :: String -> String -> Maybe [String]
getLinesWith t = filterM (Just $ isSpecialLine t) . lines
现在编译器抱怨类型不匹配:Maybe (String -> Bool) 与预期的String -> Maybe Bool 不匹配。好吧,很合理。所以我:
getLinesWith :: String -> String -> Maybe [String]
getLinesWith t = Just $ filter (isSpecialLine t) . lines
再次输入不匹配,这次Maybe (String -> [String]) 不是String -> Maybe [String]。将[String] 包装成Maybe monad 的正确语法是什么?
【问题讨论】:
-
我认为你首先不需要
Maybe。Maybe通常用于非全部功能(例如,一些无意义的输入)。