我试图理解为什么应用程序函数默认工作(不需要实现)对于像Maybe
这样的函子,但是对于其他函数没有:
例:
Just (+3) <*> (Just 3)
工作正常“开箱即用” - > 6
Left (+3) <*> Left 3
不起作用
即使我宣布Just (+3) <*> Left 4
,Either Int Int
也不起作用。
我假设99%的情况下处理成对:(f (a->b) , f a)
你必须自己实现所需的行为(笛卡尔积(f (a->b)) X (f a)
),第一个例子就是开箱即用的简单东西。
示例在(Maybe (a->b) , Either c d)
的情况下,我们需要涵盖所有4个案例:
Just - Left
Just - Right
Nothing - Left
Nothing -Right
我在这个假设中是对的吗?
Applicative
的Either
实例定义为:
instance Applicative (Either e) where ...
鉴于(<*>)
的类型是Applicative f => f (a -> b) -> f a -> f b
的Either
,它是:
Either e (a -> b) -> Either e a -> Either e b
Left
的类型是e -> Either e a
所以Left (+3)
的类型是
Num a => Either (a -> a) b
和Left 3
的类型是:
Num a => Either a b
这导致Left (+3) <*> Left 3
的类型为(Num a, Num (a -> a)) => Either (a -> a) b
,这不太可能是你想要的。
因为它是包含要操作的函数和值的类型b
,所以使用Right
构造函数确实有效:
Right (+3) <*> Right 3
=> Right 6