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