]> gitweb.michael.orlitzky.com - spline3.git/blob - src/RealFunction.hs
Add some doctest examples to RealFunction.
[spline3.git] / src / RealFunction.hs
1 {-# LANGUAGE FlexibleInstances #-}
2
3 module RealFunction (
4 RealFunction,
5 cmult,
6 fexp
7 )
8 where
9
10
11 type RealFunction a = (a -> Double)
12
13
14 -- | A 'Show' instance is required to be a 'Num' instance.
15 instance Show (RealFunction a) where
16 -- | There is nothing of value that we can display about a
17 -- function, so simply print its type.
18 show _ = "<RealFunction>"
19
20
21 -- | An 'Eq' instance is required to be a 'Num' instance.
22 instance Eq (RealFunction a) where
23 -- | Nothing else makes sense here; always return 'False'.
24 _ == _ = error "You can't compare functions for equality."
25
26
27 -- | The 'Num' instance for RealFunction allows us to perform
28 -- arithmetic on functions in the usual way.
29 instance Num (RealFunction a) where
30 (f1 + f2) x = (f1 x) + (f2 x)
31 (f1 - f2) x = (f1 x) - (f2 x)
32 (f1 * f2) x = (f1 x) * (f2 x)
33 (negate f) x = -1 * (f x)
34 (abs f) x = abs (f x)
35 (signum f) x = signum (f x)
36 fromInteger i _ = fromInteger i
37
38
39 -- | Takes a constant, and a function as arguments. Returns a new
40 -- function representing the original function times the constant.
41 --
42 -- ==== __Examples__
43 --
44 -- >>> let square x = x**2
45 -- >>> square 1
46 -- 1.0
47 -- >>> square 2
48 -- 4.0
49 -- >>> let f = cmult 2 square
50 -- >>> f 1
51 -- 2.0
52 -- >>> f 2
53 -- 8.0
54 --
55 cmult :: Double -> (RealFunction a) -> (RealFunction a)
56 cmult coeff f = (*coeff) . f
57
58
59 -- | Takes a function @f@ and an exponent @n@. Returns a new function,
60 -- @g@, defined by g(x) = (f(x))^n. This is /not/ @f@ composed
61 -- with itself @n@ times.
62 --
63 -- ==== __Examples__
64 --
65 -- >>> let square x = x**2
66 -- >>> square 2
67 -- 4.0
68 -- >>> let f = fexp square 3
69 -- >>> f 2
70 -- 64.0
71 --
72 fexp :: (RealFunction a) -> Int -> (RealFunction a)
73 fexp f n
74 | n == 0 = (\_ -> 1)
75 | otherwise = \x -> (f x)^n