2010-08-22 79 views
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) 

也许我只是太傻找出什么地方出了错,但这对我来说看起来很奇怪。

+0

另外,怎么样'不是String()'的类型签名?那么你并没有扭转定义明确的语义。另外,任一个都是Monad(好,有点...参见'Control.Monad.Error'),所以你甚至不需要“失败”。 – jrockway 2010-08-25 04:09:49

+0

我想尽可能通用类型签名。所以我做到了。 – fuz 2010-08-25 04:40:55

回答

5

看的maybe类型,并认为它应该做的:

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

如果可能的值不包含任何结果(即Nothing),maybe返回b说法。

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

你的代码只是变得

maybe (return s) fail (validate s 0) 
+0

你是对的。 (多么不好的问题)......对我感到羞耻。 – fuz 2010-08-22 15:36:23

相关问题