11module Data.These where
22
33import Prelude
4- ( ($)
5- , (<$>)
6- , (<*>)
7- , (<<<)
8- , (<>)
9- , class Applicative
10- , class Apply
11- , class Bind
12- , class Functor
13- , class Monad
14- , class Semigroup
15- , class Show
16- , show
17- , pure
18- , id
19- )
4+
5+ import Control.Extend (class Extend )
206
217import Data.Bifunctor (class Bifunctor )
228import Data.Bitraversable (class Bitraversable , class Bifoldable , bitraverse )
9+ import Data.Functor.Invariant (class Invariant , imapF )
10+ import Data.Generic (class Generic )
2311import Data.Maybe (Maybe (..))
2412import Data.Traversable (class Traversable , class Foldable , foldMap , foldl , foldr )
2513import Data.Tuple (Tuple (..))
2614
27- data These a b = This a
28- | That b
29- | Both a b
15+ data These a b
16+ = This a
17+ | That b
18+ | Both a b
19+
20+ derive instance eqThese :: (Eq a , Eq b ) => Eq (These a b )
21+ derive instance ordThese :: (Ord a , Ord b ) => Ord (These a b )
22+ derive instance genericThese :: (Generic a , Generic b ) => Generic (These a b )
3023
3124instance semigroupThese :: (Semigroup a , Semigroup b ) => Semigroup (These a b ) where
3225 append (This a) (This b) = This (a <> b)
@@ -44,6 +37,9 @@ instance functorThese :: Functor (These a) where
4437 map f (That a) = That (f a)
4538 map _ (This a) = This a
4639
40+ instance invariantThese :: Invariant (These a ) where
41+ imap = imapF
42+
4743instance foldableThese :: Foldable (These a ) where
4844 foldr f z = foldr f z <<< theseRight
4945 foldl f z = foldl f z <<< theseRight
@@ -88,17 +84,22 @@ instance applicativeThese :: Semigroup a => Applicative (These a) where
8884instance bindThese :: Semigroup a => Bind (These a ) where
8985 bind (This a) _ = This a
9086 bind (That x) k = k x
91- bind (Both a x) k = case k x of
92- This b -> This (a <> b)
93- That y -> Both a y
94- Both b y -> Both (a <> b) y
87+ bind (Both a x) k =
88+ case k x of
89+ This b -> This (a <> b)
90+ That y -> Both a y
91+ Both b y -> Both (a <> b) y
9592
9693instance monadThese :: Semigroup a => Monad (These a )
9794
95+ instance extendEither :: Extend (These a ) where
96+ extend _ (This a) = This a
97+ extend f x = map (const (f x)) x
98+
9899instance showThese :: (Show a , Show b ) => Show (These a b ) where
99- show (This x) = " This ( " <> show x <> " )"
100- show (That y) = " That ( " <> show y <> " )"
101- show (Both x y) = " Both ( " <> show x <> " ) ( " <> show y <> " )"
100+ show (This x) = " ( This " <> show x <> " )"
101+ show (That y) = " ( That " <> show y <> " )"
102+ show (Both x y) = " ( Both " <> show x <> " " <> show y <> " )"
102103
103104these :: forall a b c . (a -> c ) -> (b -> c ) -> (a -> b -> c ) -> These a b -> c
104105these l _ _ (This a) = l a
0 commit comments