笛卡尔积不适用于应用

时间:2019-04-20 20:57:22

标签: haskell cartesian-product applicative

我试图了解可应用性,以及如何将其用作K函数和N参数之间的笛卡尔积,而我无法理解为什么我不能执行以下操作:< / p>

[Just (+1),Just (+2)] <*> [Just 1 ,Just 2]渲染

错误

* Couldn't match expected type `Maybe Integer -> b'
                  with actual type `Maybe (Integer -> Integer)'
    * Possible cause: `Just' is applied to too many arguments      In the expression: Just (+ 1)      In the first argument of `(<*>)', namely `[Just (+ 1), Just (+ 2)]'
      In the expression: [Just (+ 1), Just (+ 2)] <*> [Just 1, Just 2]

我不明白,因为从定义上讲,它应该将函数移出上下文,取值并应用所有组合。

我也尝试过:

:t [pure (+1),pure (+2)] <*> [Just 1 ,Just 2] :: Num a => [a -> a]并且我不明白为什么结果类型不是值列表(而不是a->a),因为所有运算符都只期望一个参数,而我已经提供了。 / p>

有人可以照亮吗?

1 个答案:

答案 0 :(得分:13)

此处涉及两个应用层([]Maybe),因此(<*>)本身必须是可应用的:

GHCi> (<*>) <$> [Just (+1),Just (+2)] <*> [Just 1 ,Just 2]
[Just 2,Just 3,Just 3,Just 4]

此用例由Compose新类型捕获。 Nesting any two applicative functors gives rise to another applicative

GHCi> import Data.Functor.Compose
GHCi> Compose [Just (+1),Just (+2)] <*> Compose [Just 1 ,Just 2]
Compose [Just 2,Just 3,Just 3,Just 4]