哪个相当于Dual for Applicative?

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

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", [(),(),(),(),()])

我本可以发誓在Swap有一个相当于base,但我似乎无法找到它。在其他一些包装中是否有常用的等效物?

haskell
1个回答
9
投票

您正在寻找Backwardstransformers' 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)
© www.soinside.com 2019 - 2024. All rights reserved.