2 A simple homogeneous pair type with useful Functor, Applicative, and
6 module Pair ( Pair(..), unPair, toPair, swap ) where
8 #include "HsVersions.h"
12 import Control.Applicative
14 import Data.Traversable
16 data Pair a = Pair { pFst :: a, pSnd :: a }
17 -- Note that Pair is a *unary* type constructor
18 -- whereas (,) is binary
20 -- The important thing about Pair is that it has a *homogenous*
21 -- Functor instance, so you can easily apply the same function
23 instance Functor Pair where
24 fmap f (Pair x y) = Pair (f x) (f y)
26 instance Applicative Pair where
28 (Pair f g) <*> (Pair x y) = Pair (f x) (g y)
30 instance Foldable Pair where
31 foldMap f (Pair x y) = f x `mappend` f y
33 instance Traversable Pair where
34 traverse f (Pair x y) = Pair <$> f x <*> f y
36 instance Outputable a => Outputable (Pair a) where
37 ppr (Pair a b) = ppr a <+> char '~' <+> ppr b
39 unPair :: Pair a -> (a,a)
40 unPair (Pair x y) = (x,y)
42 toPair :: (a,a) -> Pair a
43 toPair (x,y) = Pair x y
45 swap :: Pair a -> Pair a
46 swap (Pair x y) = Pair y x