实现`Applicative(Free f)` [英] Implementing `Applicative (Free f)`
问题描述
Free Monad
: data Free fa = Var a
| Node(f(Free fa))
我实现了实例Functor(Free f )
:
实例Functor f => Functor(Free f)其中
fmap g(Var x)= Var(gx)
fmap g(Node x)= Node $ fmap(\y - > fmap gy)x
然后我试着执行实例Applicative(Free f)
:
实例Functor f => Applicative(Free f)其中
pure x = Var x
我的直觉是 var x
是纯粹的正确定义。
然而,不管这是否正确,我不知道如何实现<>
。
是否有必要支持以下情况?请注意,我忽略了 Var
和 Node
的构成,其中 _
。
(Var _)* (Var _)
(Var _)* (节点_)
(节点_)* (Var _)
(Node _)* (Node _)
请给我一个关于上述情况是否需要匹配的提示。 / p>
另外,请告诉我一个直觉,说明两个 Free fa
实例存在于任何一边的<>
。
使用 ap
的合法答案。如果你内嵌 ap
,你最终得到这个结果:
instance Functor f => Applicative(Free f)其中
pure = A
A a * A b = A $ a b
A a * F mb = F $ fmap a< $> mb
F ma * b = F $(* b)< $> ma
(注意:最近版本的免费
包使用这个定义,以尽可能显式。)
As For the I implemented Then I tried to implement My intuition is that However, regardless of whether that's correct, I'm not sure how to implement In particular, is it necessary to support the following cases? Note that I ignored the make-up of the Please give me a hint as to whether the above cases need to be matched. Also, please provide me with an intuition as to what it means for both Will Ness gives a perfectly legitimate answer using (Note: recent versions of the As chi showed, the first two cases can be combined:
这篇关于实现`Applicative(Free f)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
A f < * GT; x = f< $> x
Free Monad
:data Free f a = Var a
| Node (f (Free f a))
instance Functor (Free f)
:instance Functor f => Functor (Free f) where
fmap g (Var x) = Var (g x)
fmap g (Node x) = Node $ fmap (\y -> fmap g y) x
instance Applicative (Free f)
:instance Functor f => Applicative (Free f) where
pure x = Var x
var x
is the right definition of pure
.<*>
.Var
and Node
with _
.(Var _) <*> (Var _)
(Var _) <*> (Node _)
(Node _) <*> (Var _)
(Node _) <*> (Node _)
Free f a
instances to exist on either side of <*>
.ap
. If you inline ap
, you end up with this:instance Functor f => Applicative (Free f) where
pure = A
A a <*> A b = A $ a b
A a <*> F mb = F $ fmap a <$> mb
F ma <*> b = F $ (<*> b) <$> ma
free
package use this definition so as to be as explicit as possible.) A f <*> x = f <$> x