Dual
是一个新类型的封装器,它只是反转封装类型的Monoid
实例中mappend
的顺序:
>>> "hello" <> " " <> "world"
"hello world"
>>> getDual $ Dual "hello" <> Dual " " <> Dual "world"
"world hello"
同样地,也可以定义一个新类型包装器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", [(),(),(),(),()])
我狂想着在base
里有一个等效于Swap
的函数,但是我似乎找不到它。是否有其他包中常用的等效函数?
<**> :: Applicative f => f a -> f (a -> b) -> f b
。 - Simon Courtenage