maclunian
maclunian

Reputation: 8023

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.

Upvotes: 10

Views: 13795

Answers (5)

Tom Crockett
Tom Crockett

Reputation: 31579

= 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.

Upvotes: 23

jon_darkstar
jon_darkstar

Reputation: 16768

= performs assignment. or definition is probably a better word. can only do it once. this is a special operator/symbol. it is not a function

== is a function, usually infixed, that takes two inputs of typeclass Eq and returns a bool

Prelude> let a = 1
Prelude> a
1
Prelude> 5 == 5
True
Prelude> 5 == 6
False
Prelude> :t (==)
(==) :: (Eq a) => a -> a -> Bool

Upvotes: 2

aleator
aleator

Reputation: 4486

The == is an operator for comparing if two things are equal. It is quite normal haskell function with type "Eq a => a -> a -> Bool". The type tells that it works on every type of a value that implements Eq typeclass, so it is kind of overloaded.

The = on the other hand is an assignment operator, which is used to introduce definitions.

Upvotes: 1

deceze
deceze

Reputation: 522091

I'm not quite a Haskell expert yet, but as in most other languages == is a comparison operator yielding true or false, while = is the assignment operator, which in Haskell boils down to function declaration.

ghci> 5 == 5
true
ghci> "foo" == "bar"
false
ghci> let foo = "bar"

Upvotes: 1

Jordonias
Jordonias

Reputation: 5848

== is for equality

example: comparing two integers

= is assignment

example: assigning an integer to a variable

Upvotes: 0

Related Questions