1 {-# LANGUAGE CPP, NoImplicitPrelude #-}
3 -----------------------------------------------------------------------------
5 -- Module : Data.Either
6 -- Copyright : (c) The University of Glasgow 2001
7 -- License : BSD-style (see the file libraries/base/LICENSE)
9 -- Maintainer : libraries@haskell.org
10 -- Stability : experimental
11 -- Portability : portable
13 -- The Either type, and associated operations.
15 -----------------------------------------------------------------------------
19 either, -- :: (a -> c) -> (b -> c) -> Either a b -> c
20 lefts, -- :: [Either a b] -> [a]
21 rights, -- :: [Either a b] -> [b]
22 partitionEithers, -- :: [Either a b] -> ([a],[b])
27 #ifdef __GLASGOW_HASKELL__
35 #ifdef __GLASGOW_HASKELL__
38 import Test.QuickCheck
43 The 'Either' type represents values with two possibilities: a value of
44 type @'Either' a b@ is either @'Left' a@ or @'Right' b@.
46 The 'Either' type is sometimes used to represent a value which is
47 either correct or an error; by convention, the 'Left' constructor is
48 used to hold an error value and the 'Right' constructor is used to
49 hold a correct value (mnemonic: \"right\" also means \"correct\").
51 data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show)
53 -- | Case analysis for the 'Either' type.
54 -- If the value is @'Left' a@, apply the first function to @a@;
55 -- if it is @'Right' b@, apply the second function to @b@.
56 either :: (a -> c) -> (b -> c) -> Either a b -> c
57 either f _ (Left x) = f x
58 either _ g (Right y) = g y
59 #endif /* __GLASGOW_HASKELL__ */
61 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
63 -- | Extracts from a list of 'Either' all the 'Left' elements
64 -- All the 'Left' elements are extracted in order.
66 lefts :: [Either a b] -> [a]
67 lefts x = [a | Left a <- x]
69 -- | Extracts from a list of 'Either' all the 'Right' elements
70 -- All the 'Right' elements are extracted in order.
72 rights :: [Either a b] -> [b]
73 rights x = [a | Right a <- x]
75 -- | Partitions a list of 'Either' into two lists
76 -- All the 'Left' elements are extracted, in order, to the first
77 -- component of the output. Similarly the 'Right' elements are extracted
78 -- to the second component of the output.
80 partitionEithers :: [Either a b] -> ([a],[b])
81 partitionEithers = foldr (either left right) ([],[])
83 left a ~(l, r) = (a:l, r)
84 right a ~(l, r) = (l, a:r)
87 {--------------------------------------------------------------------
89 --------------------------------------------------------------------}
90 prop_partitionEithers :: [Either Int Int] -> Bool
91 prop_partitionEithers x =
92 partitionEithers x == (lefts x, rights x)