views:

97

answers:

1

Hi,

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?

+7  A: 

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.

camccann
Yes, I really forgot the indentation!Thank you very much!Now everything works fine. :)
Ben
Actually I made an algebraic datatype Function, which derives Eq and Show. I just wanted to make my posting short, so I thought I skipthe unnecessary details.Thanks again, and sorry I forgot to mark your answer as accepted.I´m new to this.
Ben
@Ben: Okay, that does sound more reasonable. And no worries about not knowing to accept--we're all here to learn.
camccann