了解如何应用haskell applicative仿函数

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

我只是有一个关于应用函子的快速问题,以帮助我掌握它们。这只是我在ghci中应用的东西。

[(+3),((-) 3),(*3)] <*> [4]
[7,-1,12]

这对我来说很有意义。基本申请。但在尝试时:

[(Just (+3)),(Just ((-) 3)),(Just (*3))] <*> [Just 4]

我收到了很多错误。我有点理解为什么;有两个数据构造函数([]Maybe)和<*>函数只“剥离”其中一个。我想要帮助我理解的是,haskell正在尝试逐步进行直到失败,以及如何绕过它并将其成功计算到:

[(Just 7),(Just -1),(Just 12)]
haskell monads applicative maybe
1个回答
9
投票

你有两个不同的Applicative实例。的确如此

Just (* 3) <*> Just 4 == Just 12

[]实例只是尝试将第一个列表中的每个“函数”应用于第二个中的每个值,因此您最终尝试应用

(Just (* 3)) (Just 4)

这是一个错误。

(更准确地说,你的Just值列表只有错误的类型才能充当<*>的第一个参数。)

相反,您需要在第一个列表上映射<*>

> (<*>) <$> [(Just (+3)),(Just ((-) 3)),(Just (*3))] <*> [Just 4]
[Just 7,Just (-1),Just 12]

(在列表中映射高阶函数是您通常首先获得包装函数列表的方式。例如,

> :t [(+3), ((-) 3), (* 3)]
[(+3), ((-) 3), (* 3)] :: Num a => [a -> a]
> :t Just <$> [(+3), ((-) 3), (* 3)]
Just <$> [(+3), ((-) 3), (* 3)] :: Num a => [Maybe (a -> a)]

)


评论中提到的Data.Functor.Compose是另一种选择。

> import Data.Functor.Compose
> :t Compose [(Just (+3)),(Just ((-) 3)),(Just (*3))]
Compose [(Just (+3)),(Just ((-) 3)),(Just (*3))]
  :: Num a => Compose [] Maybe (a -> a)
> Compose [(Just (+3)),(Just ((-) 3)),(Just (*3))] <*> Compose [Just 4]
Compose [Just 12,Just (-1),Just 12]
> getCompose <$> Compose [(Just (+3)),(Just ((-) 3)),(Just (*3))] <*> Compose [Just 4]
[Just 12,Just (-1),Just 12]

Compose的定义非常简单:

newtype Compose f g a = Compose { getCompose: f (g a) }

奇妙的是,只要fg都是(应用)仿函数,那么Compose f g也是一个(应用)仿函数。

instance (Functor f, Functor g) => Functor (Compose f g) where
    fmap f (Compose x) = Compose (fmap (fmap f) x)

instance (Applicative f, Applicative g) => Applicative (Compose f g) where
    pure x = Compose (pure (pure x))
    Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)

Applicative实例中,您可以看到我在上面使用的(<*>) <$> ...的相同用法。

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