我真的很讨厌问这种问题,但我在这里无能为力。我正在编写一个增量解析器,但由于某种原因,我无法弄清楚如何为其实现仿函数实例。这是代码转储:
输入数据类型
输入是解析器向协程产生的数据类型。它包含由协程和行尾条件操作的当前输入字符列表
data Input a = S [a] Bool deriving (Show)
instance Functor Input where
fmap g (S as x) = S (g <$> as) x
输出数据类型
输出是协程向 Parser 产生的数据类型。它可以是 Failed 消息、Done [b] 或 Partial ([a] -> Output ab),其中 [a] 是传回解析器的当前缓冲区
data Output a b = Fail String | Done [b] | Partial ([a] -> Output a b)
instance Functor (Output a) where
fmap _ (Fail s) = Fail s
fmap g (Done bs) = Done $ g <$> bs
fmap g (Partial f) = Partial $ \as -> g <$> f as
解析器
解析器接受 [a] 并产生一个缓冲区 [a] 给协程,协程返回输出 ab
data ParserI a b = PP { runPi :: [a] -> (Input a -> Output a b) -> Output a b }
函子实现
似乎我所要做的就是将函数 g 映射到协程上,如下所示:
instance Functor (ParserI a) where
fmap g p = PP $ \as k -> runPi p as (\xs -> fmap g $ k xs)
但它不输入检查:
Couldn't match type `a1' with `b'
`a1' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> ParserI a a1 -> ParserI a b
at Tests.hs:723:9
`b' is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> ParserI a a1 -> ParserI a b
at Tests.hs:723:9
Expected type: ParserI a b
Actual type: ParserI a a1