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.
41 cmult :: Double -> (RealFunction a) -> (RealFunction a)
42 cmult coeff f = (*coeff) . f
45 -- | Takes a function f and an exponent n. Returns a new function,
47 fexp :: (RealFunction a) -> Int -> (RealFunction a)
50 | otherwise = \x -> (f x)^n