0

这个小函数检查(有限)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)

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

4

1 回答 1

5

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

maybe :: b -> (a -> b) -> Maybe a -> b

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

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

你的代码就变成了

maybe (return s) fail (validate s 0)
于 2010-08-22T15:34:40.970 回答