5

Possible Duplicate:
Comparing functions in Haskell

I'm learning haskell, wanted to know is something like this possible? All I want is to compare if parameter 'function' is equal to one of the functions a or b. How to do this?

Example code:

a,b :: Integer -> Integer
a x = x+1
b x = x-1

c function parameter = if function == a 
           then ... parameter -- Do a related stuff
           else ... parameter -- Do b related stuff
4
  • I'm no Haskell expert, but in order to use the function (==) the parameters have to be part of the Eq typeclass, and I don't think functions can be part of typeclasses. Commented Nov 4, 2012 at 1:10
  • 6
    From this answer: There is not, and will never be, a way to compare two functions for equality. There is a mathematical proof that it is not possible in general. Commented Nov 4, 2012 at 1:12
  • @VincentSavard: instance Num b => Num (a -> b) where (f + g) x = f x + g x -- ... Commented Nov 4, 2012 at 2:01
  • @Fixnum: Interesting! I'm not quite familiar with the syntax (I can only write really basic programs), but there's a lot of concepts I'll have to look into! Commented Nov 4, 2012 at 2:33

1 Answer 1

2

The only case I know of where you can compare two functions for equality is if their domain has a finite number of values. For example, if you have two functions of type:

f, g :: Bool -> A

Then they are equal if they are equal for all inputs:

f == g = (f False == g False) && (f True == g True)

However, for the case of Int, comparing them on every possible value of Int is impractical and inefficient. For Integer, it can't be done since Integers are unbounded.

As @Miguel correctly pointed out in his comment, functions with non-finite domains cannot be compared for equality in general.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.