Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuiting (&&) in Haskell

Tags:

A quick question that has been bugging me lately. Does Haskell perform all the equivalence test in a function that returns a boolean, even if one returns a false value?

For example

f a b = ((a+b) == 2) && ((a*b) == 2)

If the first test returns false, will it perform the second test after the &&? Or is Haskell lazy enough to not do it and move on?

like image 909
Jonno_FTW Avatar asked Nov 22 '09 14:11

Jonno_FTW


People also ask

What do you mean by short circuiting?

short circuit. noun. a faulty or accidental connection between two points of different potential in an electric circuit, bypassing the load and establishing a path of low resistance through which an excessive current can flow. It can cause damage to the components if the circuit is not protected by a fuse.

What causes short circuiting?

They occur when a low-resistance path not suited to carry electricity receives a high-volume electrical current. In simpler terms, short circuits happen when hot wire touches a conductive object it's not supposed to. The result of a short circuit can be appliance damage, electrical shock, or even a fire.


2 Answers

Should be short circuited just like other languages. It's defined like this in the Prelude:

(&&)                    :: Bool -> Bool -> Bool
True  && x              =  x
False && _              =  False

So if the first parameter is False the 2nd never needs to be evaluated.

like image 78
Caleb Avatar answered Oct 02 '22 00:10

Caleb


Like Martin said, languages with lazy evaluation never evaluate anything that's value is not immediately needed. In a lazy language like Haskell, you get short circuiting for free. In most languages, the || and && and similar operators must be built specially into the language in order for them to short circuit evaluation. However, in Haskell, lazy evaluation makes this unnecessary. You could define a function that short circuits yourself even:

scircuit fb sb = if fb then fb else sb

This function will behave just like the logical 'or' operator. Here is how || is defined in Haskell:

True  || _ = True
False || x = x

So, to give you the specific answer to your question, no. If the left hand side of the || is true, the right hand side is never evaluated. You can put two and two together for the other operators that 'short circuit'.

like image 37
Rayne Avatar answered Oct 02 '22 00:10

Rayne