为什么GHC抱怨错误的类型?

fuz*_*fuz 0 haskell types compiler-errors brainfuck

这个小函数检查(有限的)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"
Run Code Online (Sandbox Code Playgroud)

现在,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)
Run Code Online (Sandbox Code Playgroud)

也许我太傻了,无法弄清楚出了什么问题,但对我来说这看起来很奇怪.

Dar*_*rio 5

看看它的类型maybe并思考它应该做什么:

maybe :: b -> (a -> b) -> Maybe a -> b
Run Code Online (Sandbox Code Playgroud)

如果maybe值不包含结果(即Nothing),则maybe返回b参数.

否则 - 何时Just a给出 - 它将给定函数应用于有效结果.我们fromJust这里不需要任何提取.

你的代码就变成了

maybe (return s) fail (validate s 0)
Run Code Online (Sandbox Code Playgroud)