为什么应用工作默认仅适用于Maybe

问题描述 投票:0回答:1

我试图理解为什么应用程序函数默认工作(不需要实现)对于像Maybe这样的函子,但是对于其他函数没有:

例: Just (+3) <*> (Just 3)工作正常“开箱即用” - > 6 Left (+3) <*> Left 3不起作用 即使我宣布Just (+3) <*> Left 4Either 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 我在这个假设中是对的吗?

haskell functor applicative
1个回答
7
投票

ApplicativeEither实例定义为:

instance Applicative (Either e) where ...

鉴于(<*>)的类型是Applicative f => f (a -> b) -> f a -> f bEither,它是:

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
© www.soinside.com 2019 - 2024. All rights reserved.