[英]Why does applicative work default only for Maybe
I am trying to understand why do applicative functors work by default (no implementation needed) for some functors like Maybe
but for others don't: 我试图理解为什么对于像
Maybe
这样的某些函子,应用函子默认情况下会工作(无需实现),而对于其他函子却不起作用:
Example: 例:
Just (+3) <*> (Just 3)
works fine "out of the box"- > 6
Just (+3) <*> (Just 3)
“开箱即用”-> 6
Left (+3) <*> Left 3
does not work Left (+3) <*> Left 3
不起作用
Just (+3) <*> Left 4
does not work even if i declare an Either Int Int
. 即使我声明
Either Int Int
Just (+3) <*> Left 4
也不起作用。
I assume in 99% of cases when dealing with pairs of : (f (a->b) , fa)
you must implement the desired behaviour yourself ( Cartesian Product (f (a->b)) X (fa)
) and the first example is just something simple out of the box. 我假设在99%的情况下,当处理成对的:
(f (a->b) , fa)
您必须自己实现所需的行为( 笛卡尔乘积 (f (a->b)) X (fa)
),并且第一个例子是开箱即用的简单东西。
Example In the case of (Maybe (a->b) , Either cd)
we would need to cover all 4 cases: 示例对于
(Maybe (a->b) , Either cd)
我们需要涵盖所有4种情况:
Just - Left Just - Right Nothing - Left Nothing -Right
Am i right in this assumption ? 我在这个假设中正确吗?
The Applicative
instance for Either
is defined as: Either
的Applicative
实例定义为:
instance Applicative (Either e) where ...
given the type of (<*>)
is Applicative f => f (a -> b) -> fa -> fb
for Either
that is: 给定的类型
(<*>)
是Applicative f => f (a -> b) -> fa -> fb
为Either
是:
Either e (a -> b) -> Either e a -> Either e b
The type of Left
is e -> Either ea
so the type of Left (+3)
is Left
的类型为e -> Either ea
所以Left (+3)
的类型为
Num a => Either (a -> a) b
and the type of Left 3
is: Left 3
的类型是:
Num a => Either a b
which leads to the type for Left (+3) <*> Left 3
as (Num a, Num (a -> a)) => Either (a -> a) b
which is unlikely to be what you intended. 这导致
Left (+3) <*> Left 3
为(Num a, Num (a -> a)) => Either (a -> a) b
都不是您想要的。
Since it's the type b
which contains the function and value to operate on, using the Right
constructor does work: 由于类型
b
包含要操作的函数和值,因此使用Right
构造函数确实可行:
Right (+3) <*> Right 3
=> Right 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.