Reputation: 75
I want to make functions Double -> Double an instance of the Num typeclass. I want to define the sum of two functions as sum of their images. So I wrote
instance Num Function where
f + g = (\ x -> (f x) + (g x))
Here the compiler complains he can´t tell whether I´m using Prelude.+ or Module.+ in the lambda expression. So I imported Prelude qualified as P and wrote
instance Num Function where
f + g = (\ x -> (f x) P.+ (g x))
This compiles just fine, but when I try to add two functions in GHCi
the interpreter complains again he can´t tell whether I´m using Prelude.+
or
Module.+
.
Is there any way I can solve this problem?
Upvotes: 2
Views: 184
Reputation: 77384
The compiler is complaining because you're defining a new function named +
, rather than defining an implementation of +
for a class instance. Are you forgetting to indent the function definition? You want something like this:
instance Num (Double -> Double) where
f + g = (\ x -> (f x) + (g x))
Not like this:
instance Num (Double -> Double) where
f + g = (\ x -> (f x) + (g x))
That said, a Num
instance for a function type isn't really going to work properly for various reasons, most significantly that Num
instances are required to also be instances of Eq
and Show
, neither of which can really be defined on functions in a way that makes sense.
Upvotes: 7