[英]Nested applicative functors of different types in Haskell
我想制作不同类型的嵌套applicative functor。 例如,不同类型的嵌套简单仿函数(在ghci中)可以正常工作:
Prelude> ((+2) <$>) <$> (Just [1..4])
Just [3,4,5,6]
但对于不同类型的应用函子:
Prelude> ((*) <$>) <$> (Just [1,2,3]) <*> (Just [4,5,6,7])
<interactive>:56:1: error:
* Couldn't match type `[Integer -> Integer]' with `[Integer] -> b'
不工作! 我想获得这样的东西:
Just [4,5,6,7,8,10,12,14,12,15,18,21]
我知道应用仿函数在仿函数和monad之间具有中间位置。 在关于monad变形金刚的主题之前,我可以看到这个练习是初步的。
除了嵌套升降机和fmaps之外,构建应用程序Data.Functor.Compose
函数的另一个选项是Data.Functor.Compose
:
newtype Compose f g a = Compose { getCompose :: f (g a) }
例如:
ghci> let Compose result = (*) <$> Compose (Just [1,2,3]) <*> Compose (Just [4,5,6,7])
ghci> result
Just [4,5,6,7,8,10,12,14,12,15,18,21]
Applicative
如此良好,以至于单个newtype足以组成作为实例的任何两种类型。 除了嵌套之外,还有其他方法可以将它们组合在一起,例如Product
和Day
卷积:
data Product f g a = Pair (f a) (g a)
data Day f g a = forall b c. Day (f b) (g c) (b -> c -> a)
Monad
虽然没有构图,所以我们需要为每个monad添加一个不同的新类型 ,以便用第一个monad的能力来增强其他monad。 我们称之为newtypes monad变换器。
在这种情况下,您需要:
liftA2 (*) <$> Just [1, 2, 3] <*> Just [4, 5, 6, 7]
要么:
liftA2 (liftA2 (*)) (Just [1, 2, 3]) (Just [4, 5, 6, 7])
外部… <$> … <*> …
或liftA2
对Maybe
,而内部操作在[]
。 如果您不知道这一点,您可以通过向GHCi询问您应该放在那里的类型来解决这个问题,例如使用打字孔:
:t _ <$> (Just [1 :: Int, 2, 3]) <*> (Just [4 :: Int, 5, 6, 7]) :: Maybe [Int]
它回馈:
_ :: [Int] -> [Int] -> [Int]
组合列表所需的行为是\\ xs ys -> (*) <$> xs <*> ys
,可以缩写为liftA2 (*)
。 ((*) <$>)
或fmap (*)
不起作用,因为它只是你需要的一半:它在单个列表上运行(使用Functor
),而你想要组合两个(使用Applicative
)。
当然, liftA2 (liftA2 (*))
适用于任何两个嵌套的applicative functor,它们的元素是数字的:
(Applicative f, Applicative g, Num a)
=> f (g a) -> f (g a) -> f (g a)
例如,嵌套列表:
liftA2 (liftA2 (*)) [[1], [2], [3]] [[4, 5, 6]]
== [[4,5,6],[8,10,12],[12,15,18]]
-- (Transposing the inputs transposes the output.)
liftA2 (liftA2 (*)) [[1, 2, 3]] [[4], [5], [6]]
== [[4,8,12],[5,10,15],[6,12,18]]
或列出的Maybe
:
liftA2 (liftA2 (*)) [Just 1, Nothing, Just 3] [Just 4, Nothing, Just 6]
== [Just 4, Nothing, Just 6,
Nothing, Nothing, Nothing,
Just 12, Nothing, Just 18]
甚至更奇特的东西,比如功能列表:
($ (3, 5)) <$> (liftA2 (+) <$> [fst, snd] <*> [snd, fst])
== [fst (3, 5) + snd (3, 5),
fst (3, 5) + fst (3, 5),
snd (3, 5) + snd (3, 5),
snd (3, 5) + fst (3, 5)]
== [3+5, 3+3, 5+5, 5+3]
== [8,6,10,8]
我们也可以通过前奏函数来完成这一过程。 你的第一部分很好。
((*) <$>) <$> (Just [1,2,3])
类型为Num a => Maybe [a -> a]
我们所需要的只是将Maybe monad中的应用列表映射到Maybe monad中的列表。 所以一种方法可能是将第一部分绑定到(<$> Just [4, 5, 6, 7]) . (<*>) :: Num a => [a -> b] -> Maybe [b]
(<$> Just [4, 5, 6, 7]) . (<*>) :: Num a => [a -> b] -> Maybe [b]
((*) <$>) <$> (Just [1,2,3]) >>= (<$> Just [4,5,6,7]) . (<*>)
屈服于
Just [(1*),(2*),(3*)] >>= (<$> Just [4,5,6,7]) . (<*>)
屈服于
([(1*),(2*),(3*)] <*>) <$> Just [4,5,6,7]
屈服于
Just [4,5,6,7,8,10,12,14,12,15,18,21]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.