1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Data.Either
5 -- Copyright : (c) The University of Glasgow 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : libraries@haskell.org
9 -- Stability : experimental
10 -- Portability : portable
12 -- The Either type, and associated operations.
14 -----------------------------------------------------------------------------
18 either, -- :: (a -> c) -> (b -> c) -> Either a b -> c
19 lefts, -- :: [Either a b] -> [a]
20 rights, -- :: [Either a b] -> [b]
21 partitionEithers, -- :: [Either a b] -> ([a],[b])
26 #ifdef __GLASGOW_HASKELL__
34 import Test.QuickCheck
39 The 'Either' type represents values with two possibilities: a value of
40 type @'Either' a b@ is either @'Left' a@ or @'Right' b@.
42 The 'Either' type is sometimes used to represent a value which is
43 either correct or an error; by convention, the 'Left' constructor is
44 used to hold an error value and the 'Right' constructor is used to
45 hold a correct value (mnemonic: \"right\" also means \"correct\").
47 data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show)
49 -- | Case analysis for the 'Either' type.
50 -- If the value is @'Left' a@, apply the first function to @a@;
51 -- if it is @'Right' b@, apply the second function to @b@.
52 either :: (a -> c) -> (b -> c) -> Either a b -> c
53 either f _ (Left x) = f x
54 either _ g (Right y) = g y
55 #endif /* __GLASGOW_HASKELL__ */
57 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
59 -- | Extracts from a list of 'Either' all the 'Left' elements
60 -- All the 'Left' elements are extracted in order.
62 lefts :: [Either a b] -> [a]
63 lefts x = [a | Left a <- x]
65 -- | Extracts from a list of 'Either' all the 'Right' elements
66 -- All the 'Right' elements are extracted in order.
68 rights :: [Either a b] -> [b]
69 rights x = [a | Right a <- x]
71 -- | Partitions a list of 'Either' into two lists
72 -- All the 'Left' elements are extracted, in order, to the first
73 -- component of the output. Similarly the 'Right' elements are extracted
74 -- to the second component of the output.
76 partitionEithers :: [Either a b] -> ([a],[b])
77 partitionEithers = foldr (either left right) ([],[])
79 left a (l, r) = (a:l, r)
80 right a (l, r) = (l, a:r)
83 {--------------------------------------------------------------------
85 --------------------------------------------------------------------}
86 prop_partitionEithers :: [Either Int Int] -> Bool
87 prop_partitionEithers x =
88 partitionEithers x == (lefts x, rights x)