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