繁体   English   中英

了解如何应用Haskell应用函子

[英]Understanding how haskell applicative functors are applied

我只是对应用函子有一个简单的问题,以帮助我掌握它们。 这只是我在ghci中申请的东西。

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

这对我来说很有意义。 基本应用。 但是当尝试:

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

我收到了很多错误。 我对原因有所了解。 有两个数据构造函数( []Maybe ),而<*>函数仅“剥离”其中一个。 我想帮助我理解的是haskell到底要逐步尝试直到失败,以及如何解决它并成功地将其计算为:

[(Just 7),(Just -1),(Just 12)]

您有两个不同的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提到的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 fg 也是 (应用的)仿函数。

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实例中,您可以看到与我上面使用的(<*>) <$> ...相同的用法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM