Added Data.Function (Trac ticket #979).
[ghc-base.git] / Data / Function.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Function
4 -- Copyright   :  Nils Anders Danielsson 2006
5 -- License     :  BSD-style (see the LICENSE file in the distribution)
6 --
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  portable
10 --
11 -- Simple combinators working solely on and with functions.
12
13 module Data.Function
14   ( -- * "Prelude" re-exports
15     id, const, (.), flip, ($)
16     -- * Other combinators
17   , on
18   ) where
19
20 infixl 0 `on`
21
22 -- | @(*) \`on\` f = \\x y -> f x * f y@.
23 --
24 -- Typical usage: @'Data.List.sortBy' ('compare' \`on\` 'fst')@.
25 --
26 -- Algebraic properties:
27 --
28 -- * @(*) \`on\` 'id' = (*)@ (if @(*) ∉ {⊥, 'const' ⊥}@)
29 --
30 -- * @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@
31 --
32 -- * @'flip' on f . 'flip' on g = 'flip' on (g . f)@
33
34 -- Proofs (so that I don't have to edit the test-suite):
35
36 --   (*) `on` id
37 -- =
38 --   \x y -> id x * id y
39 -- =
40 --   \x y -> x * y
41 -- = { If (*) /= _|_ or const _|_. }
42 --   (*)
43
44 --   (*) `on` f `on` g
45 -- =
46 --   ((*) `on` f) `on` g
47 -- =
48 --   \x y -> ((*) `on` f) (g x) (g y)
49 -- =
50 --   \x y -> (\x y -> f x * f y) (g x) (g y)
51 -- =
52 --   \x y -> f (g x) * f (g y)
53 -- =
54 --   \x y -> (f . g) x * (f . g) y
55 -- =
56 --   (*) `on` (f . g)
57 -- =
58 --   (*) `on` f . g
59
60 --   flip on f . flip on g
61 -- =
62 --   (\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g
63 -- =
64 --   (\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)
65 -- =
66 --   \(*) -> (*) `on` g `on` f
67 -- = { See above. }
68 --   \(*) -> (*) `on` g . f
69 -- =
70 --   (\h (*) -> (*) `on` h) (g . f)
71 -- =
72 --   flip on (g . f)
73
74 on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
75 (*) `on` f = \x y -> f x * f y