实施 Cont Applicative 实例
Implementing Cont Applicative instance
我在为 Cont
实现 Applicative 实例时遇到以下错误。
Couldn't match expected type ‘r’ with actual type ‘Cont r b’ ‘r’ is
a rigid type variable bound by ...
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
。我不确定我哪里弄错了。
很明显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))
我在为 Cont
实现 Applicative 实例时遇到以下错误。
Couldn't match expected type ‘r’ with actual type ‘Cont r b’ ‘r’ is a rigid type variable bound by ...
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
。我不确定我哪里弄错了。
很明显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))