Matt
Matt

Reputation: 1704

Brand new to Haskell, why does this function loop forever?

Context: I am less than a week into figuring Haskell out, I'm enjoying myself so far, but this one is stumping me. This seems the simplest example that demonstrates my problem:

I have the following Type defined.

data AnInteger = A Integer
instance Eq AnInteger where
  a == a' = a == a'

But when I try to use it

Screenshot of ghci infinite looping

I get what appears to be an infinite loop. What's going on here that I'm not getting?

How can I correct the syntax to provide the desired output of True?

Upvotes: 1

Views: 158

Answers (1)

sepp2k
sepp2k

Reputation: 370112

You're defining the == operator by saying that a is equal to a' iff a is equal to a'. Logically this is a tautology.

In terms of program logic it's an infinite loop, as applying the == function to two arguments will apply it again to those same arguments, infinitely.

What you probably intended to do was to use == to compare the integers wrapped in your AnIntegers, rather than the AnIntegers themselves. To do this, you'll first need to use pattern matching to unwrap them like this:

(A a) == (A a') = a == a'

Upvotes: 8

Related Questions