[Haskell-beginners] if ands
Chaddaï Fouché
chaddai.fouche at gmail.com
Fri Nov 6 14:53:25 EST 2009
On Fri, Nov 6, 2009 at 10:03 AM, Deniz Dogan <deniz.a.m.dogan at gmail.com> wrote:
>>> If you have an if statement like
>>>
>>> if (a&&b) then fun else fun'
>>>
>>> and a is false, does GHC actually bother to check b?
>>
>
> Note that Haskell is far from the only programming language that is
> smart about this. I actually can't think of a single programming
> language implementation that I know of which isn't this smart...
>
> For what it's worth, Haskell (and others) is smart about ORs as well.
> In (x || y), y will only be evaluated if x is False.
Right, almost every programming language act this way, which is why
(&&) and (||) are sometimes called short-circuit boolean operators.
What's interesting is not that Haskell does it for (&&) and (||), it's
that those operators aren't primitives in Haskell but normal functions
defined in the Prelude, their behavior is just lazy evaluation at
work...
That's also why you can write the functions and() and or() as easily as :
and :: [Bool] -> Bool
and = foldr (&&) True
or :: [Bool] -> Bool
or = foldr (||) False
And get a nice short-circuiting behavior....
--
Jedaï
More information about the Beginners
mailing list