0
这个小函数检查(有限)Brainfuck字符串的有效性。它检查[
和]
是否平衡。该代码是非常简单,编写为尾递归:为什么GHC抱怨错误的类型?
-- 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)
也许我只是太傻找出什么地方出了错,但这对我来说看起来很奇怪。
另外,怎么样'不是String()'的类型签名?那么你并没有扭转定义明确的语义。另外,任一个都是Monad(好,有点...参见'Control.Monad.Error'),所以你甚至不需要“失败”。 – jrockway 2010-08-25 04:09:49
我想尽可能通用类型签名。所以我做到了。 – fuz 2010-08-25 04:40:55