哪个相当于Dual for Applicative?

时间:2018-03-05 17:28:07

标签: haskell

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,但我似乎无法找到它。在其他一些包装中是否有常用的等效物?

1 个答案:

答案 0 :(得分:9)

您正在寻找来自transformers' Control.Applicative.BackwardsBackwards

-- | 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)