@@ -2,6 +2,7 @@ module Data.Functor.Coproduct where
22
33import Prelude
44
5+ import Data.Bifunctor (bimap )
56import Data.Either (Either (..), either )
67import Data.Foldable (class Foldable , foldMap , foldl , foldr )
78import Data.Traversable (class Traversable , traverse , sequence )
@@ -15,19 +16,28 @@ unCoproduct (Coproduct x) = x
1516
1617-- | Left injection
1718left :: forall f g a . f a -> Coproduct f g a
18- left = Coproduct <<< Left
19+ left fa = Coproduct ( Left fa)
1920
2021-- | Right injection
2122right :: forall f g a . g a -> Coproduct f g a
22- right = Coproduct <<< Right
23+ right ga = Coproduct ( Right ga)
2324
2425-- | Eliminate a coproduct by providing eliminators for the left and
2526-- | right components
2627coproduct :: forall f g a b . (f a -> b ) -> (g a -> b ) -> Coproduct f g a -> b
27- coproduct f g = either f g <<< unCoproduct
28+ coproduct f g (Coproduct e) = either f g e
29+
30+ -- | Change the underlying functors in a coproduct
31+ bihoistCoproduct
32+ :: forall f g h i
33+ . (f ~> h )
34+ -> (g ~> i )
35+ -> Coproduct f g
36+ ~> Coproduct h i
37+ bihoistCoproduct natF natG (Coproduct e) = Coproduct (bimap natF natG e)
2838
2939instance functorCoproduct :: (Functor f , Functor g ) => Functor (Coproduct f g ) where
30- map f = Coproduct <<< coproduct ( Left <<< (<$>) f) (Right <<< (<$>) f )
40+ map f ( Coproduct e) = Coproduct (bimap (map f) (map f) e )
3141
3242instance foldableCoproduct :: (Foldable f , Foldable g ) => Foldable (Coproduct f g ) where
3343 foldr f z = coproduct (foldr f z) (foldr f z)
@@ -36,8 +46,8 @@ instance foldableCoproduct :: (Foldable f, Foldable g) => Foldable (Coproduct f
3646
3747instance traversableCoproduct :: (Traversable f , Traversable g ) => Traversable (Coproduct f g ) where
3848 traverse f = coproduct
39- ((<$>) (Coproduct <<< Left ) <<< traverse f)
40- ((<$>) (Coproduct <<< Right ) <<< traverse f)
49+ (map (Coproduct <<< Left ) <<< traverse f)
50+ (map (Coproduct <<< Right ) <<< traverse f)
4151 sequence = coproduct
42- ((<$>) (Coproduct <<< Left ) <<< sequence)
43- ((<$>) (Coproduct <<< Right ) <<< sequence)
52+ (map (Coproduct <<< Left ) <<< sequence)
53+ (map (Coproduct <<< Right ) <<< sequence)
0 commit comments