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