x< *> y< $> z在Haskell [英] x <*> y <$> z in Haskell
问题描述
我试图了解一些Haskell源代码,并且有时会遇到这种结构:
I'm trying to understand some Haskell source code, and I encountered this structure some times:
x <*> y <$> z
例如
(+) <*> (+1) <$> a
有人可以向我解释这种结构吗?我知道它可以翻译为fmap a (+ a + 1)
,但是我无法建立连接
Can somebody explain this structure to me? I get that it translates to fmap a (+ a + 1)
, but I can't make the connection
推荐答案
让我们开始:
x <*> y <$> z
加上括号,它变为:
(x <*> y) <$> z
鉴于(<$>) :: Functor f => (a -> b) -> f a -> f b
,我们有:
x <*> y :: a -> b
z :: Functor f => f a
鉴于(<*>) :: Applicative g => g (c -> d) -> g c -> g d
,我们有:
x :: Applicative g => g (c -> d)
y :: Applicative g => g c
x <*> y :: Applicative g => g d
结合最后几个结果,我们得到:
Combining the last few results, we get:
g d ~ a -> b
g ~ (->) a
d ~ b
x :: a -> c -> b
y :: a -> c
x <*> y :: a -> b
因此:
(\x y z -> x <*> y <$> z) :: Functor f => (a -> c -> b) -> (a -> c) -> f a -> f b
现在知道使用了函数实例中的(<*>)
,我们还可以替换其定义:
Now knowing that (<*>)
from the function instance is being used, we can also substitute its definition:
x <*> y <$> z
(\r -> x r (y r)) <$> z
在您的示例中,x = (+)
,y = (+1)
和z = a
,所以我们得到...
In your example, x = (+)
, y = (+1)
and z = a
, so we get...
(\r -> r + (r + 1)) <$> a
...,这会将a
中的每个值加到自身加上一个:
... which adds each value in a
to itself plus one:
GHCi> (+) <*> (+1) <$> [0..3]
[1,3,5,7]
GHCi> ((+) <*> (+1) <$> (*5)) 2
21
这篇关于x< *> y< $> z在Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!