1 {-# LANGUAGE FlexibleInstances #-}
10 type RealFunction a = (a -> Double)
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>"
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."
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)
34 (signum f) x = signum (f x)
35 fromInteger i _ = fromInteger i
38 -- | Takes a constant, and a function as arguments. Returns a new
39 -- function representing the original function times the constant.
43 -- >>> let square x = x**2
48 -- >>> let f = cmult 2 square
54 cmult :: Double -> (RealFunction a) -> (RealFunction a)
55 cmult coeff f = (*coeff) . f
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.
64 -- >>> let square x = x**2
67 -- >>> let f = fexp square 3
71 fexp :: (RealFunction a) -> Int -> (RealFunction a)
74 | otherwise = \x -> (f x)^n