Haskell: overloading issues: translator can't tell what to use +

I want to make Double -> Double functions an instance of the Num class. I want to define the sum of two functions as the sum of their images. So I wrote

instance Num Function where

f + g = (\ x -> (f x) + (g x))

      

Here the compiler is complaining that it can't tell if I'm using Prelude + or Module. + in lambda expression. So I imported the 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 to GHCi, the translator complains again that it can't tell if I use Prelude.+

or Module.+

. Is there a way to solve this problem?

+2


a source to share


1 answer


The compiler is complaining because you are defining a new named function +

rather than defining an implementation +

for an instance of the class. Are you forgetting to deviate from the function definition? You want something like this:

instance Num (Double -> Double) where
    f + g = (\ x -> (f x) + (g x))

      

Not this way:



instance Num (Double -> Double) where

f + g = (\ x -> (f x) + (g x))

      

However, an instance Num

for a function type doesn't actually work Num

as expected for various reasons, especially since instances must also be instances Eq

and Show

neither of which can actually be defined on functions in a way that makes sense.

+7


a source







All Articles