1 {-# LANGUAGE CPP, NoImplicitPrelude #-}
2 #ifdef __GLASGOW_HASKELL__
3 {-# LANGUAGE DeriveDataTypeable, DeriveGeneric, StandaloneDeriving #-}
6 -----------------------------------------------------------------------------
8 -- Module : Data.Either
9 -- Copyright : (c) The University of Glasgow 2001
10 -- License : BSD-style (see the file libraries/base/LICENSE)
12 -- Maintainer : libraries@haskell.org
13 -- Stability : experimental
14 -- Portability : portable
16 -- The Either type, and associated operations.
18 -----------------------------------------------------------------------------
22 either, -- :: (a -> c) -> (b -> c) -> Either a b -> c
23 lefts, -- :: [Either a b] -> [a]
24 rights, -- :: [Either a b] -> [b]
25 partitionEithers, -- :: [Either a b] -> ([a],[b])
30 #ifdef __GLASGOW_HASKELL__
37 import GHC.Generics (Generic)
39 #ifdef __GLASGOW_HASKELL__
42 import Test.QuickCheck
47 The 'Either' type represents values with two possibilities: a value of
48 type @'Either' a b@ is either @'Left' a@ or @'Right' b@.
50 The 'Either' type is sometimes used to represent a value which is
51 either correct or an error; by convention, the 'Left' constructor is
52 used to hold an error value and the 'Right' constructor is used to
53 hold a correct value (mnemonic: \"right\" also means \"correct\").
55 data Either a b = Left a | Right b
56 deriving (Eq, Ord, Read, Show, Generic)
58 -- | Case analysis for the 'Either' type.
59 -- If the value is @'Left' a@, apply the first function to @a@;
60 -- if it is @'Right' b@, apply the second function to @b@.
61 either :: (a -> c) -> (b -> c) -> Either a b -> c
62 either f _ (Left x) = f x
63 either _ g (Right y) = g y
64 #endif /* __GLASGOW_HASKELL__ */
66 INSTANCE_TYPEABLE2(Either,eitherTc,"Either")
68 -- | Extracts from a list of 'Either' all the 'Left' elements
69 -- All the 'Left' elements are extracted in order.
71 lefts :: [Either a b] -> [a]
72 lefts x = [a | Left a <- x]
74 -- | Extracts from a list of 'Either' all the 'Right' elements
75 -- All the 'Right' elements are extracted in order.
77 rights :: [Either a b] -> [b]
78 rights x = [a | Right a <- x]
80 -- | Partitions a list of 'Either' into two lists
81 -- All the 'Left' elements are extracted, in order, to the first
82 -- component of the output. Similarly the 'Right' elements are extracted
83 -- to the second component of the output.
85 partitionEithers :: [Either a b] -> ([a],[b])
86 partitionEithers = foldr (either left right) ([],[])
88 left a ~(l, r) = (a:l, r)
89 right a ~(l, r) = (l, a:r)
92 {--------------------------------------------------------------------
94 --------------------------------------------------------------------}
95 prop_partitionEithers :: [Either Int Int] -> Bool
96 prop_partitionEithers x =
97 partitionEithers x == (lefts x, rights x)