1 {-# LANGUAGE FlexibleInstances #-}
11 type RealFunction a = (a -> Double)
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>"
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."
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)
35 (signum f) x = signum (f x)
36 fromInteger i _ = fromInteger i
39 -- | Takes a constant, and a function as arguments. Returns a new
40 -- function representing the original function times the constant.
44 -- >>> let square x = x**2
49 -- >>> let f = cmult 2 square
55 cmult :: Double -> (RealFunction a) -> (RealFunction a)
56 cmult coeff f = (*coeff) . f
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.
65 -- >>> let square x = x**2
68 -- >>> let f = fexp square 3
72 fexp :: (RealFunction a) -> Int -> (RealFunction a)
75 | otherwise = \x -> (f x)^n