实现`Applicative(Free f)` [英] Implementing `Applicative (Free f)`

查看:76
本文介绍了实现`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

  A f < * GT; x = f< $> x 


For the Free Monad:

data Free f a = Var a
               | Node (f (Free f a)) 

I implemented 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

Then I tried to implement instance Applicative (Free f):

instance Functor f => Applicative (Free f) where
    pure x                = Var x

My intuition is that var x is the right definition of pure.

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 Var and Node with _.

(Var _) <*> (Var _)
(Var _) <*> (Node _)
(Node _) <*> (Var _)
(Node _) <*> (Node _)

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 Free f a instances to exist on either side of <*>.

解决方案

Will Ness gives a perfectly legitimate answer using 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

(Note: recent versions of the free package use this definition so as to be as explicit as possible.)

As chi showed, the first two cases can be combined:

  A f <*> x = f <$> x

这篇关于实现`Applicative(Free f)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆