]> gitweb.michael.orlitzky.com - spline3.git/blob - src/RealFunction.hs
d461ae2f7d95fd1babe673d576c185bcee1e8de4
[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 cmult :: Double -> (RealFunction a) -> (RealFunction a)
42 cmult coeff f = (*coeff) . f
43
44
45 -- | Takes a function f and an exponent n. Returns a new function,
46 -- f^n.
47 fexp :: (RealFunction a) -> Int -> (RealFunction a)
48 fexp f n
49 | n == 0 = (\_ -> 1)
50 | otherwise = \x -> (f x)^n