Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between == and = in Haskell

I still have trouble getting my head around the difference between the == and = in Haskell. I know the former has something to do with being an overloaded type and the latter 'gives the result' of the function but I just can't seem to get my head around it! Any help would be much appreciated.

like image 645
maclunian Avatar asked May 13 '11 05:05

maclunian


People also ask

Can functions be compared for equality in Haskell?

Most notably, in Haskell, functions are not in the Eq typeclass (in general). Not any two functions can be compared for equality in Haskell.

What is not equal in Haskell?

The /= operator means "is not equal". It's supposed to be reminiscent of the mathematical "≠" symbol (i.e., an equals sign with a diagonal line through it).

What does -> mean in Haskell?

(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.

What does ++ do Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.


1 Answers

= is a special reserved symbol in Haskell meaning "is defined as". It is used to introduce definitions. That is, you use it to create new values and functions which may be referenced in the definitions of other values and functions.

== is not a reserved symbol but just a run-of-the-mill function of type Eq a => a -> a -> Bool. It happens to be declared in a type class (Eq), but there's nothing extraordinary about it. You could hide the built-in declaration of == and redefine it to whatever you wanted. But normally it means "is equal to", and because it is part of a type class, you can define (overload) it to mean whatever you want "equality" to mean for your particular type.

For example:

data Foo = Foo Int

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

Note that I used = to define == for Foo!

A pithy way to think of the difference is that = asserts equality at compile time, whereas == checks for equality at runtime.

like image 88
Tom Crockett Avatar answered Sep 21 '22 18:09

Tom Crockett