Short-circuit evaluation: Difference between revisions

no edit summary
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
No edit summary
Line 1,926:
false || false = false
</pre>
 
=={{header|Lambdatalk}}==
Short-circuiting evaluation of boolean expressions has been the default since the first versions of lambdatalk.
<lang scheme>
{def A {lambda {:bool} :bool}} -> A
{def B {lambda {:bool} :bool}} -> B
 
{and {A true} {B true}} -> true
{and {A true} {B false}} -> false
{and {A false} {B true}} -> false
{and {A false} {B false}} -> false
 
{or {A true} {B true}} -> true
{or {A true} {B false}} -> true
{or {A false} {B true}} -> true
{or {A false} {B false}} -> false
</lang>
 
Some more words about short-circuit evaluation. Lambdatalk comes with the {if "bool" then "one" else "two"} special form where "one" or "two" are not evaluated until "bool" is. This behaviour prevents useless computing and allows recursive processes. For instance, the naïve fibonacci function quickly leads to extensive computings.
<lang scheme>
 
{def fib
{lambda {:n}
{if {< :n 2}
then 1
else {+ {fib {- :n 1}} {fib {- :n 2}}}}}}
-> fib
 
1) Using the if special form:
 
{if true then {+ 1 2} else {fib 29}}
-> 3 // {fib 29} is not evaluated
 
{if false then {+ 1 2} else {fib 29}}
-> 832040 // {fib 29} is evaluated in 5847ms
 
2) The if special form can't be simply replaced by a pair:
 
{def when {P.new {+ 1 2} {fib 29}}} // inner expressions are
{P.left {when}} -> 3 // both evaluated before
{P.right {when}} -> 832040 // and we don't want that
 
3) We can delay evaluation using lambdas:
 
{def when
{P.new {lambda {} {+ 1 2}} // will return a lambda
{lambda {} {fib 22}} }} // to be evaluated later
-> when
{{P.left {when}}} -> 3 // lambdas are evaluated
{{P.right {when}}} -> 832040 // after choice using {}
 
</lang>
 
=={{header|Liberty BASIC}}==