" " <> "world" "hello wor-6ren">
gpt4 book ai didi

haskell - 相当于 Dual for Applicative 的地方在哪里?

转载 作者:行者123 更新时间:2023-12-01 08:48:15 24 4
gpt4 key购买 nike

Dual 是一个 newtype-wrapper,只是颠倒了 mappend 的顺序对于包裹类型的 Monoid实例:

>>> "hello" <> " " <> "world"
"hello world"
>>> getDual $ Dual "hello" <> Dual " " <> Dual "world"
"world hello"

等效地,可以定义一个 newtype-wrapper Swap颠倒 <*> 的顺序对于包裹类型的 Applicative实例:
newtype Swap f a = Swap { getSwap :: f a } deriving Functor
instance Applicative f => Applicative (Swap f) where
pure = Swap . pure
Swap mf <*> Swap ma = Swap $ (\a f -> f a) <$> ma <*> mf

>>> ("hello", replicate) <*> (" ", 5) <*> ("world", ())
("hello world", [(),(),(),(),()])
>>> getSwap $ Swap ("hello", replicate) <*> Swap (" ",5) <*> Swap ("world", ())
("world hello", [(),(),(),(),()])

我可以发誓有一个相当于 Swapbase ,但我似乎找不到它。在其他一些包中是否有常用的等价物?

最佳答案

您正在寻找 Backwards ,来自 transformers' Control.Applicative.Backwards :

-- | The same functor, but with an 'Applicative' instance that performs
-- actions in the reverse order.
newtype Backwards f a = Backwards { forwards :: f a }

-- etc.

-- | Apply @f@-actions in the reverse order.
instance (Applicative f) => Applicative (Backwards f) where
pure a = Backwards (pure a)
{-# INLINE pure #-}
Backwards f <*> Backwards a = Backwards (a <**> f)
{-# INLINE (<*>) #-}

(<**>) ,来自 Control.Applicative ,正如你所期望的:
-- | A variant of '<*>' with the arguments reversed.
(<**>) :: Applicative f => f a -> f (a -> b) -> f b
(<**>) = liftA2 (\a f -> f a)

关于haskell - 相当于 Dual for Applicative 的地方在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com