【发布时间】:2016-03-29 08:40:19
【问题描述】:
我正在尝试在 Haskell 中将此作为 Monad 的实例:
data Parser a = Done ([a], String) | Fail String
现在我尝试使用这段代码使其成为 Monad 的实例:
instance Functor Parser where
fmap = liftM
instance Applicative Parser where
pure = return
(<*>) = ap
instance Monad Parser where
return xs = Done ([], xs)
Done (xs, s) >>= f = Done (concat (map f xs)), s)
但这显然不起作用,因为绑定函数中的函数f 是a -> M b 类型。所以(map f xs) 函数会生成一个M b-things 列表。它实际上应该列出b 的列表。我怎样才能在 Haskell 中做到这一点?
注意:GHC 7.10.3 给出的实际错误是:
SuperInterpreter.hs:71:27:
Couldn't match expected type `String' with actual type `a'
`a' is a rigid type variable bound by
the type signature for return :: a -> Parser a
at SuperInterpreter.hs:71:5
Relevant bindings include
xs :: a (bound at SuperInterpreter.hs:71:12)
return :: a -> Parser a (bound at SuperInterpreter.hs:71:5)
In the expression: xs
In the first argument of `Done', namely `([], xs)'
SuperInterpreter.hs:72:45:
Couldn't match type `Parser b' with `[b]'
Expected type: a -> [b]
Actual type: a -> Parser b
Relevant bindings include
f :: a -> Parser b (bound at SuperInterpreter.hs:72:22)
(>>=) :: Parser a -> (a -> Parser b) -> Parser b
(bound at SuperInterpreter.hs:72:5)
In the first argument of `map', namely `f'
In the first argument of `concat', namely `(map f xs)'
Failed, modules loaded: none.
【问题讨论】:
-
在你
map f xs之后,检查结果列表:要么你有一些Fails,要么你没有。在前者中,您想返回Fail,我猜是(?)。在后者中,您可以访问Done构造函数中的对列表。 -
当列表中的一个元素是失败时,我确实想返回失败,但是我如何访问构造函数中的对列表呢?我真的不知道该怎么做。
-
这里的
a是什么——这是解析器的结果吗?String是什么?通常你有一个返回值和一个带有剩余/未解析字符串的返回值,解析器是一个接受输入字符串并返回的函数 - 例如 - 一些结果和剩余字符串的元组