这个小函数检查(有限的)Brainfuck字符串的有效性。它检查[
和]
是否平衡。代码非常简单,并且编写为尾递归:
-- checks Brainfuck for validity.
validateBrainfuck :: Monad m => String -> m String
validateBrainfuck s = maybe (return s) (fail . fromJust) (validate s 0) where
validate :: String -> Int -> Maybe String -- Here inversed: String means error
validate (']':_ ) 0 = Just "Too many closing brackets"
validate (']':xs) c = validate xs (pred c)
validate ('[':xs) c = validate xs (succ c)
validate ( x :xs) c = validate xs c
validate [] 0 = Nothing
validate [] _ = Just "Too many opening brackets"
现在,GHC抱怨打字问题:
Brainfuck.hs:62:58:
Couldn't match expected type `Maybe String'
against inferred type `[Char]'
Expected type: Maybe (Maybe String)
Inferred type: Maybe String
In the third argument of `maybe', namely `(validate s 0)'
In the expression:
maybe (return s) (fail . fromJust) (validate s 0)
也许我太傻了,无法弄清楚出了什么问题,但对我来说这看起来很奇怪。
答案 0 :(得分:5)
查看maybe
的类型,并考虑它应该做什么:
maybe :: b -> (a -> b) -> Maybe a -> b
如果maybe值不包含结果(即Nothing
),maybe
将返回b
参数。
否则 - 当给出Just a
时 - 它将给定的函数应用于有效结果。我们这里不需要fromJust
提取。
您的代码变为
maybe (return s) fail (validate s 0)