Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell avoid never-ending recursion in boolean value definitions?

Years ago I read about how Haskell compares boolean expressions and I wanted to see if I can use the same concept in my project (F#), but I don't understand how it works:

Source: https://hackage.haskell.org/package/ghc-prim-0.10.0/docs/src/GHC.Classes.html#%3D%3D

x /= y               = not (x == y)
x == y               = not (x /= y) 

It makes perfect sense, but how doesn't it end in a never-ending recursion?


Context: in my project I have spent and unspent coins and I think they could be handled similar to booleans, where a coin is unspent when it is not spent and it is spent when it is not unspent.

like image 703
lontivero Avatar asked Aug 24 '26 06:08

lontivero


1 Answers

Those are default methods of the Eq typeclass. This means that if some type instantiates Eq and does not provide an implementation of ==, it will be defined as not (x /= y). And if it does not provide an implementation of /=, it will be defined as not (x == y). If it doesn't provide an implementation of either method, you will indeed get infinite recursion.

Note also the {-# MINIMAL (==) | (/=) #-} annotation after those two lines. This means "a minimal implementation of Eq will define either == or /=" and instructs the compiler to produce a warning when you create an instance that doesn't define at least one of those methods.

like image 191
sepp2k Avatar answered Aug 26 '26 07:08

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!