[Haskell-cafe] A probably-stupid question about a Prelude implementation.

Bulat Ziganshin bulat.ziganshin at gmail.com
Fri Jun 22 14:28:23 EDT 2007

Hello Michael,

Friday, June 22, 2007, 7:31:17 PM, you wrote:

no surprise - you got a lot of answers :)  it is the best part of
Haskell, after all :)

the secret Haskell weapon is lazy evaluation which makes *everything*
short-circuited. just consider standard (&&) definition:

(&&) False _ = False
(&&) True  x = x

this means that as far as first argument of (&&) is False, we don't
even examine second one. and because everything is lazy evaluated,
this second argument passed as non-evaluated *expression*. if we never
examined it, it will be never evaluated:

Prelude> True && (0 `div` 0>0)
*** Exception: divide by zero
Prelude> False && (0 `div` 0>0)

in particular, this allows to create your own control structures. and
another example is that you found: infinite list may be processed as
far as you may calculate result using only finite part of list:

Prelude> take 10 [1..]
Prelude> and (cycle [True, False])

in particular, last example calculated as

True && False && ...

where "..." remains uncalculated because we find final answer after
examining second list element. i suggest you to use textual
substitution to see how the last "and" call are translated into this
sequence of "&&" applications. this substitution is real process of
evaluating haskell code, it is called "graph reduction" by scientists :)

Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com

More information about the Haskell-Cafe mailing list