笛卡尔积不适用于应用

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

我试图理解应用以及如何将它用作K函数和N参数之间的笛卡尔积,我无法理解为什么我不能做以下事情:

[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),因为所有运算符只期望一个参数,并且我已经提供了它。

有人可以解释一下吗?

haskell cartesian-product applicative
1个回答
13
投票

这里涉及两个应用层([]Maybe),所以(<*>)本身必须适用于:

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

这个用例由Compose newtype捕获。 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]

.

© www.soinside.com 2019 - 2024. All rights reserved.