Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening in the background when an instance of a typeclass is defined wrongly?

I was busy with an exercise in the "Typeclasses" chapter of Haskell Book, and I solved it as the following:

data TisAnInteger =
  TisAn Integer

instance Eq TisAnInteger where
  (==) (TisAn x) (TisAn y) = x == y

So that I can use it in GHCi REPL like:

λ> TisAn 9 == TisAn 9
True
λ> TisAn 9 == TisAn 8
False

but while playing with it and asking "what if?" questions, I've realized that the following compiles, too:

data TisAnInteger =
  TisAn Integer

instance Eq TisAnInteger where
  (==) x y = x == y

and when I try to run something similar in GHCi:

λ> TisAn 9 == TisAn 8
Interrupted.
λ> TisAn 9 == TisAn 9
Interrupted.

Well Interrupted. because I hit Ctrl+C after a few seconds, GHCi was not printing anything.

I'm trying to understand two things:

  1. Why does it compile without any complaints?
  2. What's happening in GHCi in the background while nothing is printed at all (at least for many seconds)? Does it enter an infinite loop, etc.? (I can see that the CPU usage of ghc goes to over 90% during that time)

Any hints, pointers to docs, etc. for me so that I can enhance my understanding of the above phenomenon?

like image 467
Emre Sevinç Avatar asked Jan 07 '23 02:01

Emre Sevinç


1 Answers

It's simply entering an infinite loop. You are defining (==) x y as x == y, which is equivalent to... (==) x y. It's as if you've said f(x) = f(x).

like image 170
asthasr Avatar answered Jan 14 '23 12:01

asthasr