2 A simple homogeneous pair type with useful Functor, Applicative, and
\r
3 Traversable instances.
\r
6 module Pair ( Pair(..), unPair, toPair, swap ) where
\r
8 #include "HsVersions.h"
\r
12 import Control.Applicative
\r
13 import Data.Foldable
\r
14 import Data.Traversable
\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
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
26 instance Applicative Pair where
\r
28 (Pair f g) <*> (Pair x y) = Pair (f x) (g y)
\r
30 instance Foldable Pair where
\r
31 foldMap f (Pair x y) = f x `mappend` f y
\r
33 instance Traversable Pair where
\r
34 traverse f (Pair x y) = Pair <$> f x <*> f y
\r
36 instance Outputable a => Outputable (Pair a) where
\r
37 ppr (Pair a b) = ppr a <+> char '~' <+> ppr b
\r
39 unPair :: Pair a -> (a,a)
\r
40 unPair (Pair x y) = (x,y)
\r
42 toPair :: (a,a) -> Pair a
\r
43 toPair (x,y) = Pair x y
\r
45 swap :: Pair a -> Pair a
\r
46 swap (Pair x y) = Pair y x
\r