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
,但我似乎无法找到它。在其他一些包装中是否有常用的等效物?
答案 0 :(得分:9)
您正在寻找来自transformers' Control.Applicative.Backwards
的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)