Package environments
[ghc.git] / compiler / utils / Pair.hs
1 {-
2 A simple homogeneous pair type with useful Functor, Applicative, and
3 Traversable instances.
4 -}
5
6 {-# LANGUAGE CPP #-}
7
8 module Pair ( Pair(..), unPair, toPair, swap ) where
9
10 #include "HsVersions.h"
11
12 import Outputable
13 import Control.Applicative
14 #if __GLASGOW_HASKELL__ < 709
15 import Data.Foldable
16 import Data.Monoid
17 import Data.Traversable
18 #endif
19
20 data Pair a = Pair { pFst :: a, pSnd :: a }
21 -- Note that Pair is a *unary* type constructor
22 -- whereas (,) is binary
23
24 -- The important thing about Pair is that it has a *homogenous*
25 -- Functor instance, so you can easily apply the same function
26 -- to both components
27 instance Functor Pair where
28 fmap f (Pair x y) = Pair (f x) (f y)
29
30 instance Applicative Pair where
31 pure x = Pair x x
32 (Pair f g) <*> (Pair x y) = Pair (f x) (g y)
33
34 instance Foldable Pair where
35 foldMap f (Pair x y) = f x `mappend` f y
36
37 instance Traversable Pair where
38 traverse f (Pair x y) = Pair <$> f x <*> f y
39
40 instance Outputable a => Outputable (Pair a) where
41 ppr (Pair a b) = ppr a <+> char '~' <+> ppr b
42
43 unPair :: Pair a -> (a,a)
44 unPair (Pair x y) = (x,y)
45
46 toPair :: (a,a) -> Pair a
47 toPair (x,y) = Pair x y
48
49 swap :: Pair a -> Pair a
50 swap (Pair x y) = Pair y x