[英]Reader Applicative's Apply Function
Looking at the reader or environment applicative
from Brent Yorgey's UPenn 2013 Lecture : 观看Brent Yorgey的UPenn 2013 讲座中的
reader or environment applicative
:
instance Functor ((->) e) where
fmap = (.)
instance Applicative ((->) e) where
pure = const
f <*> x = \e -> (f e) (x e)
I'm trying to gain intuition for the Applicative instance. 我试图获得Applicative实例的直觉。
Given: 鉴于:
(<*>) :: Applicative f => f (a -> b) -> fa -> fb
then how does \\e -> (fe) (xe)
result in the fb
type? 那么
\\e -> (fe) (xe)
导致fb
类型?
If we substitute ((->) e)
for f
(remembering that this is a function with e
as its argument type), we get: 如果我们用
((->) e)
代替f
(记住这是一个以e
为参数类型的函数),我们得到:
(<*>) :: f (a -> b) -> f a -> f b
(<*>) :: ((->) e) (a -> b) -> ((->) e) a -> ((->) e) b -- Replace f with ((->) e)
(<*>) :: (e -> (a -> b)) -> (e -> a) -> (e -> b) -- Apply ((->) e)
(<*>) :: (e -> a -> b) -> (e -> a) -> e -> b -- Remove unneeded parentheses
A key thing to remember is that ((->) e) a
is the same as e -> a
. 要记住的一个关键事项是
((->) e) a
与e -> a
相同。 The notation can look a bit misleading at first. 这个符号最初看起来有点误导。
The only implementation for this type is the one you have provided in your question. 此类型的唯一实现是您在问题中提供的实现。 This definition can also be written as:
该定义也可以写成:
f <*> x = \e -> f e (x e)
or, using prefix notation: 或者,使用前缀表示法:
(<*>) f x e = f e (x e)
Looks like S combinator to me. 看起来像S组合对我来说。 (It's not an answer, it's a comment.)
(这不是答案,而是评论。)
My explanation is this: 我的解释如下:
Applicative operation is pretty much like zipping. 应用操作非常像拉链。 In our specific case we have two entities (
f
and a
) that both depend on e
. 在我们的具体情况中,我们有两个实体(
f
和a
)都依赖于e
。 So zipping them together produces another entity that depends on e again: and when called, it uses the same e for the left and for the right part. 因此,将它们压缩在一起会产生另一个依赖于e的实体:当被调用时,它对左侧和右侧使用相同的e。 Compare to this:
与此相比:
We have f 0 , f 1 , f 2 , etc, and a 0 , a 1 , a 2 , etc. When zipping them, we get (f 0 ,a 0 ), (f 1 ,a 1 ), (f 2 ,a 2 ) etc. 我们有f 0 ,f 1 ,f 2等,以及0 ,a 1 ,a 2等。当压缩它们时,我们得到(f 0 ,a 0 ),(f 1 ,a 1 ),(f 2 , 2 )等
In applicative case, we also apply fi
to ai
, so we get (f 0 a 0 ), (f 1 a 1 ), (f 2 a 2 ) etc. Note that we use the same index for f
and a
. 在应用案例中,我们也将
fi
应用于ai
,因此我们得到(f 0 a 0 ),(f 1 a 1 ),(f 2 a 2 )等。请注意,我们对f
和a
使用相同的索引。 If we consider the index as environment (we "read" the index), here we go, it's the same thing. 如果我们将索引视为环境(我们“读取”索引),那么我们就去了,这是一回事。 And also, that's how S combinator works.
而且,这就是S组合器的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.