实现Cont适用实例

时间:2018-12-29 04:22:28

标签: haskell continuation-passing

Cont实现Applicative实例时,出现以下错误。

  

无法将预期类型“ r”与实际类型“ Cont r b”“ r”匹配   由...约束的刚性类型变量。

newtype Cont r a = Cont {(>>-) :: (a -> r) -> r}

instance Functor (Cont r) where
  -- fmap :: (a -> b) -> (Cont r) a -> (Cont r) b
  fmap f (Cont cps_a) = Cont $ \cps -> cps_a (cps . f)

instance Applicative (Cont r) where
  -- pure :: a -> Cont r a
  pure x = Cont ($ x)
  -- (<*>) Cont r (a -> b) -> Cont r a -> Cont r b
  (Cont cps_f) <*> cont_cps_a = cps_f (\f -> fmap f cont_cps_a)

我正在尝试使用fmap来定义(<*>),从左侧cps值中提取f,然后从右侧cps值中fmap f中提取。我不确定在哪里弄错了。

1 个答案:

答案 0 :(得分:4)

很明显,表达式cps_f (\f -> fmap f cont_cps_a)的类型无效。自

fmap f cont_cps_a :: Cont r b

\f -> fmap f cont_cps_a :: (a->b)->Cont r b

cps_f :: ((a->b)->r)->r

cps_f需要参数类型为(a->b)->r,但现在是(a->b)->Cont r b

代替使用fmap,您仍然可以实现<*>运算符,类似于您的fmap函数的实现方式

(Cont cps_f) <*> Cont cps_a = Cont $ \cps_b -> cps_f (\f -> cps_a (cps_b . f))