on 9ad401b help sign in
89 lines 2.6 kB history raw
1-- | This module defines a datatype `Pair` together with a few useful instances
2-- | and helper functions. Note that this is not just `Tuple a a` but rather a
3-- | list with exactly two elements. Specifically, the `Functor` instance maps
4-- | over both values (in contrast to the `Functor` instance for `Tuple a`).
5module Data.Pair
6 ( Pair(..)
7 , (~)
8 , fst
9 , snd
10 , curry
11 , uncurry
12 , swap
13 ) where
15import Prelude
17import Data.Foldable (class Foldable)
18import Data.Traversable (class Traversable)
19import Data.Distributive (class Distributive)
21import Test.QuickCheck.Arbitrary (class Arbitrary, arbitrary)
23-- | A pair simply consists of two values of the same type.
24data Pair a = Pair a a
26infixl 6 Pair as ~
28-- | Returns the first component of a pair.
29fst ∷ ∀ a. Pair a → a
30fst (x ~ _) = x
32-- | Returns the second component of a pair.
33snd ∷ ∀ a. Pair a → a
34snd (_ ~ y) = y
36-- | Turn a function that expects a pair into a function of two arguments.
37curry ∷ ∀ a b. (Pair a → b) → a → a → b
38curry f x y = f (x ~ y)
40-- | Turn a function of two arguments into a function that expects a pair.
41uncurry ∷ ∀ a b. (a → a → b) → Pair a → b
42uncurry f (x ~ y) = f x y
44-- | Exchange the two components of the pair
45swap ∷ ∀ a. Pair a → Pair a
46swap (x ~ y) = y ~ x
48derive instance eqPair ∷ Eq a ⇒ Eq (Pair a)
50derive instance ordPair ∷ Ord a ⇒ Ord (Pair a)
52instance showPair ∷ Show a ⇒ Show (Pair a) where
53 show (x ~ y) = "(" <> show x <> " ~ " <> show y <> ")"
55instance functorPair ∷ Functor Pair where
56 map f (x ~ y) = f x ~ f y
58instance applyPair ∷ Apply Pair where
59 apply (f ~ g) (x ~ y) = f x ~ g y
61instance applicativePair ∷ Applicative Pair where
62 pure x = x ~ x
64instance bindPair ∷ Bind Pair where
65 bind (x ~ y) f = fst (f x) ~ snd (f y)
67instance monadPair ∷ Monad Pair
69instance semigroupPair ∷ Semigroup a ⇒ Semigroup (Pair a) where
70 append (x1 ~ y1) (x2 ~ y2) = (x1 <> x2) ~ (y1 <> y2)
72instance monoidPair ∷ Monoid a ⇒ Monoid (Pair a) where
73 mempty = mempty ~ mempty
75instance foldablePair ∷ Foldable Pair where
76 foldr f z (Pair x y) = x `f` (y `f` z)
77 foldl f z (Pair x y) = (z `f` x) `f` y
78 foldMap f (Pair x y) = f x <> f y
80instance traversablePair ∷ Traversable Pair where
81 traverse f (Pair x y) = Pair <$> f x <*> f y
82 sequence (Pair mx my) = Pair <$> mx <*> my
84instance distributivePair ∷ Distributive Pair where
85 distribute xs = map fst xs ~ map snd xs
86 collect f xs = map (fst <<< f) xs ~ map (snd <<< f) xs
88instance arbitraryPair ∷ Arbitrary a ⇒ Arbitrary (Pair a) where
89 arbitrary = Pair <$> arbitrary <*> arbitrary