Short-circuit evaluation: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: syntax coloured)
m (syntax highlighting fixup automation)
Line 32:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F a(v)
print(‘ ## Called function a(#.)’.format(v))
R v
Line 45:
V x = a(i) & b(j)
print(‘Calculating: y = a(i) or b(j)’)
V y = a(i) | b(j)</langsyntaxhighlight>
 
{{out}}
Line 80:
 
Source Code for the module:
<langsyntaxhighlight lang="6502asm">;DEFINE 0 AS FALSE, $FF as true.
False equ 0
True equ 255
Line 184:
db "A OR B IS TRUE",0
BoolText_A_or_B_False:
db "A OR B IS FALSE",0</langsyntaxhighlight>
 
 
The relevant code for the actual invoking of the functions:
<langsyntaxhighlight lang="6502asm">lda #True
sta z_B
lda #True
Line 199:
jsr Func_A_or_B
jmp *</langsyntaxhighlight>
 
And finally the output:
Line 205:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC a(BYTE x)
PrintF(" a(%B)",x)
RETURN (x)
Line 238:
OD
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Short-circuit_evaluation.png Screenshot from Atari 8-bit computer]
Line 255:
=={{header|Ada}}==
Ada has built-in short-circuit operations '''and then''' and '''or else''':
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Short_Circuit is
Line 281:
end loop;
end loop;
end Test_Short_Circuit;</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 300:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
Note: The "brief" ''conditional clause'' ( ~ | ~ | ~ ) is a the standard's ''shorthand'' for enforcing ''short-circuit evaluation''. Moreover, the coder is able to define their own '''proc'''[edures] and '''op'''[erators] that implement ''short-circuit evaluation'' by using Algol68's ''proceduring''.
<langsyntaxhighlight lang="algol68">PRIO ORELSE = 2, ANDTHEN = 3; # user defined operators #
OP ORELSE = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ),
ANDTHEN = (BOOL a, PROC BOOL b)BOOL: ( a | b | a );
Line 337:
print(("T ANDTHEN T = ", a(TRUE) ANDTHEN (BOOL:b(TRUE)), new line))
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 353:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68">test:(
 
PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a),
Line 377:
END CO
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 392:
=={{header|ALGOL W}}==
In Algol W the boolean "and" and "or" operators are short circuit operators.
<langsyntaxhighlight lang="algolw">begin
 
logical procedure a( logical value v ) ; begin write( "a: ", v ); v end ;
Line 406:
write( "---" );
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 433:
(As a statement, rather than an expression, the ''if ... then ... else'' structure does not compose – unlike ''cond'' or ''? :'', it can not be nested inside expressions)
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
map(test, {|and|, |or|})
Line 486:
end map
 
</syntaxhighlight>
</lang>
 
 
Line 509:
=={{header|AutoHotkey}}==
In AutoHotkey, the boolean operators, '''and''', '''or''', and ternaries, short-circuit:
<syntaxhighlight lang="autohotkey">i = 1
<lang AutoHotkey>i = 1
j = 1
x := a(i) and b(j)
Line 524:
MsgBox, b() was called with the parameter "%p%".
Return, p
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Short-circuit evalation is done in logical AND (&&) and logical OR (||) operators:
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
print (a(1) && b(1))
Line 544:
print " y:"y
return y
}</langsyntaxhighlight>
{{out}}
<pre>
Line 560:
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">TEST(0,0)
TEST(0,1)
TEST(1,0)
Line 581:
Lbl B
r₁
Return</langsyntaxhighlight>
 
=={{header|BaCon}}==
BaCon supports short-circuit evaluation.
 
<langsyntaxhighlight lang="freebasic">' Short-circuit evaluation
FUNCTION a(f)
PRINT "FUNCTION a"
Line 611:
PRINT "TRUE or FALSE"
y = a(TRUE) OR b(FALSE)
PRINT y</langsyntaxhighlight>
 
{{out}}
Line 632:
=={{header|Batch File}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang="dos">%=== Batch Files have no booleans. ===%
%=== I will instead use 1 as true and 0 as false. ===%
 
Line 678:
echo. calls func b
set bool_b=%1
goto :EOF</langsyntaxhighlight>
{{Out}}
<pre>AND
Line 715:
=={{header|BBC BASIC}}==
Short-circuit operators aren't implemented directly, but short-circuit AND can be simulated using cascaded IFs. Short-circuit OR can be converted into a short-circuit AND using De Morgan's laws.
<langsyntaxhighlight lang="bbcbasic"> REM TRUE is represented as -1, FALSE as 0
FOR i% = TRUE TO FALSE
FOR j% = TRUE TO FALSE
Line 742:
DEFFNboolstring(bool%)
IF bool%=0 THEN ="FALSE" ELSE="TRUE"</langsyntaxhighlight>
This gives the results shown below:
<pre>For x=a(TRUE) AND b(TRUE)
Line 772:
Bracmat has no booleans. The closest thing is the success or failure of an expression. A function is not called if the argument fails, so we have to use a trick to pass 'failure' to a function. Here it is accomplished by an extra level of indirection: two == in the definition of 'false' (and 'true', for symmetry) and two !! when evaluating the argument in the functions a and b. The backtick is another hack. This prefix tells Bracmat to look the other way if the backticked expression fails and to continue as if the expression succeeded. A neater way is to introduce an extra OR operator. That solution would have obscured the core of the current task.
Short-circuit evaluation is heavily used in Bracmat code. Although not required, it is a good habit to exclusively use AND (&) and OR (|) operators to separate expressions, as the code below exemplifies.
<langsyntaxhighlight lang="bracmat">( (a=.out$"I'm a"&!!arg)
& (b=.out$"I'm b"&!!arg)
& (false==~)
Line 800:
& done
);
</syntaxhighlight>
</lang>
Output:
<pre>Testing false AND false
Line 825:
=={{header|C}}==
Boolean operators <nowiki>&&</nowiki> and || are shortcircuit operators.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
 
Line 856:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 888:
}
}
}</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">a
False and False = False
 
Line 916:
 
a
True or True = True</langsyntaxhighlight>
 
=={{header|C++}}==
Just like C, boolean operators <nowiki>&&</nowiki> and || are shortcircuit operators.
<langsyntaxhighlight lang="cpp">#include <iostream>
 
bool a(bool in)
Line 946:
test(true, true);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>a
Line 971:
=={{header|Clojure}}==
The print/println stuff in the doseq is kinda gross, but if you include them all in a single print, then the function traces are printed before the rest (since it has to evaluate them before calling print).
<langsyntaxhighlight Clojurelang="clojure">(letfn [(a [bool] (print "(a)") bool)
(b [bool] (print "(b)") bool)]
(doseq [i [true false] j [true false]]
Line 977:
(println (or (a i) (b j)))
(print i "AND" j " = ")
(println (and (a i) (b j)))))</langsyntaxhighlight>
{{out}}
<pre>true OR true = (a)true
Line 989:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun a (F)
(print 'a)
F )
Line 1,001:
(and (a (car x)) (b (car(cdr x))))
(format t "~%(or ~S)" x)
(or (a (car x)) (b (car(cdr x)))))</langsyntaxhighlight>
{{out}}
(and (NIL NIL))
Line 1,026:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
T a(T)(T answer) {
Line 1,046:
immutable r2 = a(x) || b(y);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,075:
=={{header|Delphi}}==
Delphi supports short circuit evaluation by default. It can be turned off using the {$BOOLEVAL OFF} compiler directive.
<langsyntaxhighlight Delphilang="delphi">program ShortCircuitEvaluation;
 
{$APPTYPE CONSOLE}
Line 1,106:
end;
end;
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
Line 1,112:
{{trans|Swift}}
 
<langsyntaxhighlight lang="dyalect">func a(v) {
print(nameof(a), terminator: "")
return v
Line 1,137:
testMe(false, true)
testMe(true, false)
testMe(true, true)</langsyntaxhighlight>
 
{{out}}
Line 1,171:
=={{header|E}}==
E defines <code>&amp;&amp;</code> and <code>||</code> in the usual short-circuiting fashion.
<langsyntaxhighlight lang="e">def a(v) { println("a"); return v }
def b(v) { println("b"); return v }
 
def x := a(i) && b(j)
def y := b(i) || b(j)</langsyntaxhighlight>
Unusually, E is an expression-oriented language, and variable bindings (which are expressions) are in scope until the end of the nearest enclosing <code>{ ... }</code> block. The combination of these features means that some semantics must be given to a binding occurring inside of a short-circuited alternative.
<langsyntaxhighlight lang="e">def x := a(i) && (def funky := b(j))</langsyntaxhighlight>
The choice we make is that <code>funky</code> is ordinary if the right-side expression was evaluated, and otherwise is <em>ruined</em>; attempts to access the variable give an error.
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,204:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,237:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Short_circuit do
defp a(bool) do
IO.puts "a( #{bool} ) called"
Line 1,258:
end
 
Short_circuit.task</langsyntaxhighlight>
 
{{out}}
Line 1,292:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( short_circuit_evaluation ).
 
Line 1,315:
io:fwrite( "~p orelse ~p~n", [Boolean1, Boolean2] ),
io:fwrite( "=> ~p~n", [a(Boolean1) orelse b(Boolean2)] ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,350:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let a (x : bool) = printf "(a)"; x
let b (x : bool) = printf "(b)"; x
 
Line 1,356:
|> List.iter (fun (x, y) ->
printfn "%b AND %b = %b" x y ((a x) && (b y))
printfn "%b OR %b = %b" x y ((a x) || (b y)))</langsyntaxhighlight>
Output
<pre>(a)(b)true AND true = true
Line 1,369:
=={{header|Factor}}==
<code>&&</code> and <code>||</code> perform short-circuit evaluation, while <code>and</code> and <code>or</code> do not. <code>&&</code> and <code>||</code> both expect a sequence of quotations to evaluate in a short-circuit manner. They are smart combinators; that is, they infer the number of arguments taken by the quotations. If you opt not to use the smart combinators, you can also use words like <code>0&&</code> and <code>2||</code> where the arity of the quotations is dictated.
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit.smart io prettyprint ;
IN: rosetta-code.short-circuit
 
Line 1,382:
"t || f = " write { [ t a ] [ f b ] } || .
"t && t = " write { [ t a ] [ t b ] } && .
"t || t = " write { [ t a ] [ t b ] } || .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,396:
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Main
{
static Bool a (Bool value)
Line 1,423:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,449:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ Short-circuit evaluation definitions from Wil Baden, with minor name changes
: ENDIF postpone THEN ; immediate
 
Line 1,476:
I A IF J B IF 1 ELSE END-PRIOR-IF 0 ENDIF ." ANDIF=" .bool CR
I A 0= IF J B IF END-PRIOR-IF 1 ELSE 0 ENDIF ." ORELSE=" .bool CR
LOOP LOOP ;</langsyntaxhighlight>
{{out}}
<pre>A=true B=true ANDIF=true
Line 1,490:
{{works with|Fortran|90 and later}}
Using an <code>IF .. THEN .. ELSE</code> construct
<langsyntaxhighlight lang="fortran">program Short_Circuit_Eval
implicit none
 
Line 1,540:
write(*, "(a,l1,a)") "Called function b(", value, ")"
end function
end program</langsyntaxhighlight>
{{out}}
<pre>Calculating x = a(F) and b(F)
Line 1,579:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function a(p As Boolean) As Boolean
Line 1,607:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,637:
=={{header|Go}}==
Short circuit operators are <nowiki>&&</nowiki> and ||.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,668:
test(true, false)
test(true, true)
}</langsyntaxhighlight>
{{out}}
<pre>Testing a(false) && b(false)
Line 1,700:
=={{header|Groovy}}==
Like all C-based languages (of which I am aware), Groovy short-circuits the logical and (<nowiki>&&</nowiki>) and logical or (||) operations, but not the bitwise and (<nowiki>&</nowiki>) and bitwise or (|) operations.
<langsyntaxhighlight lang="groovy">def f = { println ' AHA!'; it instanceof String }
def g = { printf ('%5d ', it); it > 50 }
 
Line 1,714:
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert g(200) || f('sss')</langsyntaxhighlight>
{{out}}
<pre>bitwise
Line 1,729:
=={{header|Haskell}}==
[[Lazy evaluation]] makes it possible for user-defined functions to be short-circuited. An expression will not be evaluated as long as it is not [[pattern matching|pattern matched]]:
<langsyntaxhighlight lang="haskell">module ShortCircuit where
 
import Prelude hiding ((&&), (||))
Line 1,746:
 
main = mapM_ print ( [ a p || b q | p <- [False, True], q <- [False, True] ]
++ [ a p && b q | p <- [False, True], q <- [False, True] ])</langsyntaxhighlight>
{{out}}
<pre>
Line 1,771:
</pre>
One can force the right-hand arguemnt to be evaluated first be using the alternate definitions:
<langsyntaxhighlight lang="haskell">_ && False = False
False && True = False
_ && _ = True
Line 1,777:
_ || True = True
True || False = True
_ || _ = False</langsyntaxhighlight>
{{out}}
<pre>
Line 1,802:
</pre>
The order of evaluation (in this case the original order again) can be seen in a more explicit form by [[syntactic sugar|desugaring]] the pattern matching:
<langsyntaxhighlight lang="haskell">p && q = case p of
False -> False
_ -> case q of
Line 1,812:
_ -> case q of
True -> True
_ -> False</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,823:
* Rather than have the tasks print their own name, we will just utilize built-in tracing which will be more informative.
This use of procedures as values is somewhat contrived but serves us well for demonstration purposes. In practice this approach would be strained since failure results aren't re-captured as values (and can't easily be).
<langsyntaxhighlight Iconlang="icon">procedure main()
&trace := -1 # ensures functions print their names
 
Line 1,841:
procedure false() #: fails always
fail # for clarity but not needed as running into end has the same effect
end</langsyntaxhighlight>
Sample output for a single case:<pre>i,j := procedure true, procedure false
i & j:
Line 1,855:
=={{header|Io}}==
{{trans|Ruby}}
<langsyntaxhighlight Iolang="io">a := method(bool,
writeln("a(#{bool}) called." interpolate)
bool
Line 1,873:
writeln
)
)</langsyntaxhighlight>
{{output}}
<pre>a(true) called.
Line 1,905:
=={{header|J}}==
See the J wiki entry on [[j:Essays/Short Circuit Boolean|short circuit booleans]].
<langsyntaxhighlight lang="j">labeled=:1 :'[ smoutput@,&":~&m'
A=: 'A ' labeled
B=: 'B ' labeled
and=: ^:
or=: 2 :'u^:(-.@v)'</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="j"> (A and B) 1
B 1
A 1
Line 1,924:
B 0
A 0
0</langsyntaxhighlight>
Note that J evaluates right-to-left.
 
Line 1,931:
=={{header|Java}}==
In Java the boolean operators <code>&&</code> and <code>||</code> are short circuit operators. The eager operator counterparts are <code>&</code> and <code>|</code>.
<langsyntaxhighlight lang="java">public class ShortCirc {
public static void main(String[] args){
System.out.println("F and F = " + (a(false) && b(false)) + "\n");
Line 1,955:
return b;
}
}</langsyntaxhighlight>
{{out}}
<pre>a
Line 1,989:
Short-circuiting evaluation of boolean expressions has been the default since the first versions of JavaScript.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,010:
return [x, y, z];
})();</langsyntaxhighlight>
 
The console log shows that in each case (the binding of all three values), only the left-hand part of the expression (the application of ''a(expr)'') was evaluated – ''b(expr)'' was skipped by logical short-circuiting.
Line 2,026:
=={{header|jq}}==
jq's 'and' and 'or' are short-circuit operators. The following demonstration, which follows the "awk" example above, requires a version of jq with the built-in filter 'stderr'.
<langsyntaxhighlight lang="jq">def a(x): " a(\(x))" | stderr | x;
 
def b(y): " b(\(y))" | stderr | y;
Line 2,033:
"or:", (a(true) or b(true)),
"and:", (a(false) and b(true)),
"or:", (a(false) or b(true))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f Short-circuit-evaluation.jq
and:
" a(true)"
Line 2,049:
" a(false)"
" b(true)"
true</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia does have short-circuit evaluation, which works just as you expect it to:
 
<langsyntaxhighlight lang="julia">a(x) = (println("\t# Called a($x)"); return x)
b(x) = (println("\t# Called b($x)"); return x)
 
Line 2,062:
println("\nCalculating: y = a($i) || b($j)"); y = a(i) || b(j)
println("\tResult: y = $y")
end</langsyntaxhighlight>
{{out}}
<pre>Calculating: x = a(true) && b(true)
Line 2,101:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun a(v: Boolean): Boolean {
Line 2,122:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,154:
Short-circuiting evaluation of boolean expressions has been the default since the first versions of lambdatalk.
<langsyntaxhighlight lang="scheme">
{def A {lambda {:bool} :bool}} -> A
{def B {lambda {:bool} :bool}} -> B
Line 2,167:
{or {A false} {B true}} -> true
{or {A false} {B false}} -> false
</syntaxhighlight>
</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.
<langsyntaxhighlight lang="scheme">
 
{def fib
Line 2,202:
{{P.right {when}}} -> 832040 // after choice using {}
 
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
LB does not have short-circuit evaluation. Implemented with IFs.
<langsyntaxhighlight lang="lb">print "AND"
for i = 0 to 1
for j = 0 to 1
Line 2,240:
print ,"calls func b"
b = t
end function </langsyntaxhighlight>
{{out}}
<pre>AND
Line 2,276:
=={{header|LiveCode}}==
Livecode uses short-circuit evaluation.
<langsyntaxhighlight LiveCodelang="livecode">global outcome
function a bool
put "a called with" && bool & cr after outcome
Line 2,299:
end repeat
put outcome
end mouseUp</langsyntaxhighlight>
 
=={{header|Logo}}==
The <code>AND</code> and <code>OR</code> predicates may take either expressions which are all evaluated beforehand, or lists which are short-circuit evaluated from left to right only until the overall value of the expression can be determined.
<langsyntaxhighlight lang="logo">and [notequal? :x 0] [1/:x > 3]
(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y < 3])</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function a(i)
print "Function a(i) called."
return i
Line 2,323:
i = false
x = a(i) and b(i); print ""
y = a(i) or b(i)</langsyntaxhighlight>
 
=={{header|Maple}}==
Built-in short circuit evaluation
<langsyntaxhighlight Maplelang="maple">a := proc(bool)
printf("a is called->%s\n", bool):
return bool:
Line 2,342:
y := a(i) or b(j):
od:
od:</langsyntaxhighlight>
{{Out|Output}}
<pre>calculating x := a(i) and b(j)
Line 2,367:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has built-in short-circuit evaluation of logical expressions.
<langsyntaxhighlight Mathematicalang="mathematica">a[in_] := (Print["a"]; in)
b[in_] := (Print["b"]; in)
a[False] && b[True]
a[True] || b[False]</langsyntaxhighlight>
Evaluation of the preceding code gives:
<pre>a
Line 2,377:
True</pre>
Whereas evaluating this:
<langsyntaxhighlight Mathematicalang="mathematica">a[True] && b[False]</langsyntaxhighlight>
Gives:
<pre>a
Line 2,385:
=={{header|MATLAB}} / {{header|Octave}}==
Short-circuit evalation is done in logical AND (&&) and logical OR (||) operators:
<langsyntaxhighlight lang="matlab"> function x=a(x)
printf('a: %i\n',x);
end;
Line 2,395:
a(0) && b(1)
a(1) || b(1)
a(0) || b(1)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="matlab"> > a(1) && b(1);
a: 1
b: 1
Line 2,406:
> a(0) || b(1);
a: 0
b: 1</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE ShortCircuit;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,450:
Print(TRUE,FALSE);
ReadChar
END ShortCircuit.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
MUMPS evaluates every expression it encounters, so we have to use conditional statements to do a short circuiting of the expensive second task.
<langsyntaxhighlight MUMPSlang="mumps">SSEVAL1(IN)
WRITE !,?10,$STACK($STACK,"PLACE")
QUIT IN
Line 2,475:
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
KILL Z
QUIT</langsyntaxhighlight>
{{out}}
<pre>USER>D SSEVAL3^ROSETTA
Line 2,498:
=={{header|Nanoquery}}==
Nanoquery does not short-circuit by default, so short-circuit logic functions have been implemented by nested ifs.
<langsyntaxhighlight lang="nanoquery">def short_and(bool1, bool2)
global a
global b
Line 2,544:
 
println "T and T = " + short_and(true, true) + "\n"
println "T or T = " + short_or(true, true) + "\n"</langsyntaxhighlight>
{{out}}
<pre>a called.
Line 2,576:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
 
class ShortCircuit
Line 2,606:
WriteLine("False || False: {0}", a(f) || b(f));
}
}</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">a
b
True && True : True
Line 2,627:
a
b
False || False: False</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|ooRexx}}
Like [[OoRexx]], [[NetRexx]] allows a list of expressions in the condition part of <tt>If</tt> and <tt>When</tt>. Evaluation ends with the first of these expressions resulting in <tt>boolean true</tt>.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,661:
Say '--b returns' state
Return state
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,684:
=={{header|Nim}}==
Nim produces code which uses short-circuit evaluation.
<langsyntaxhighlight lang="nim">proc a(x): bool =
echo "a called"
result = x
Line 2,693:
 
let x = a(false) and b(true) # echoes "a called"
let y = a(true) or b(true) # echoes "a called"</langsyntaxhighlight>
 
=={{header|Objeck}}==
In Objeck the Boolean operators <code>&</code> and <code>|</code> short circuit.
<langsyntaxhighlight lang="objeck">class ShortCircuit {
function : a(a : Bool) ~ Bool {
"a"->PrintLine();
Line 2,729:
"T or T = {$result}"->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let a r = print_endline " > function a called"; r
let b r = print_endline " > function b called"; r
 
Line 2,755:
print_endline "==== Testing or ====";
test_this test_or;
;;</langsyntaxhighlight>
{{out}}
==== Testing and ====
Line 2,781:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (a x)
(print " (a) => " x)
Line 2,807:
'(#t #t #f #f)
'(#t #f #t #f))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,845:
ooRexx allows a list of expressions in the condition part of If and When.
Evaluation ends with the first of these expressions resulting in .false (or 0).
<langsyntaxhighlight lang="oorexx">Parse Version v
Say 'Version='v
If a() | b() Then Say 'a and b are true'
Line 2,860:
a: Say 'a returns .true'; Return .true
b: Say 'b returns 1'; Return 1
</syntaxhighlight>
</lang>
{{out}}
<pre>Version=REXX-ooRexx_4.2.0(MT)_32-bit 6.04 22 Feb 2014
Line 2,880:
=={{header|Oz}}==
Oz' <code>andthen</code> and <code>orelse</code> operators are short-circuiting, as indicated by their name. The library functions <code>Bool.and</code> and <code>Bool.or</code> are not short-circuiting, on the other hand.
<langsyntaxhighlight lang="oz">declare
fun {A Answer}
AnswerS = {Value.toVirtualString Answer 1 1}
Line 2,904:
Y = {A I} orelse {B J}
end
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="oz">Calculating: X = {A I} andthen {B J}
% Called function {A false} -> false
Calculating: Y = {A I} orelse {B J}
Line 2,928:
% Called function {B true} -> true
Calculating: Y = {A I} orelse {B J}
% Called function {A true} -> true</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Note that <code>|</code> and <code>&</code> are deprecated versions of the GP short-circuit operators.
<langsyntaxhighlight lang="parigp">a(n)={
print(a"("n")");
a
Line 2,945:
and(A,B)={
a(A) && b(B)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
===Standard Pascal===
Standard Pascal doesn't have native short-circuit evaluation.
<langsyntaxhighlight lang="pascal">program shortcircuit(output);
 
function a(value: boolean): boolean;
Line 2,990:
scandor(true, false);
scandor(true, true);
end.</langsyntaxhighlight>
 
===Turbo Pascal===
Turbo Pascal allows short circuit evaluation with a compiler switch:
<langsyntaxhighlight lang="pascal">program shortcircuit;
 
function a(value: boolean): boolean;
Line 3,025:
scandor(true, false);
scandor(true, true);
end.</langsyntaxhighlight>
===Extended Pascal===
The extended Pascal standard introduces the operators <code>and_then</code> and <code>or_else</code> for short-circuit evaluation.
<langsyntaxhighlight lang="pascal">program shortcircuit(output);
 
function a(value: boolean): boolean;
Line 3,058:
scandor(true, false);
scandor(true, true);
end.</langsyntaxhighlight>
Note: GNU Pascal allows <code>and then</code> and <code>or else</code> as alternatives to <code>and_then</code> and <code>or_else</code>.
 
=={{header|Perl}}==
Perl uses short-circuit boolean evaluation.
<langsyntaxhighlight Perllang="perl">sub a { print 'A'; return $_[0] }
sub b { print 'B'; return $_[0] }
 
Line 3,076:
 
# Test and display
test();</langsyntaxhighlight>
{{out}}
<pre>a(1) && b(1): AB
Line 3,089:
=={{header|Phix}}==
In Phix all expressions are short circuited
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
Line 3,114:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 3,128:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de a (F)
(msg 'a)
F )
Line 3,141:
(println I Op J '-> (Op (a I) (b J))) ) )
'(NIL NIL T T)
'(NIL T NIL T) )</langsyntaxhighlight>
{{out}}
<pre>a
Line 3,165:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">int(0..1) a(int(0..1) i)
{
write(" a\n");
Line 3,184:
write(" %d || %d\n", @args);
a(args[0]) || b(args[1]);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,210:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">short_circuit_evaluation:
procedure options (main);
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
Line 3,244:
end;
end;
end short_circuit_evaluation;</langsyntaxhighlight>
{{out|Results}}
<pre>
Line 3,282:
=={{header|PowerShell}}==
PowerShell handles this natively.
<langsyntaxhighlight lang="powershell"># Simulated fast function
function a ( [boolean]$J ) { return $J }
Line 3,314:
( a $True ) -and ( b $False )
( a $True ) -and ( b $True )
} | Select TotalMilliseconds</langsyntaxhighlight>
{{out}}
<pre>True
Line 3,333:
Prolog has not functions but predicats succeed of fail.
Tested with SWI-Prolog. Should work with other dialects.
<langsyntaxhighlight Prologlang="prolog">short_circuit :-
( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl,
Line 3,358:
b(X) :-
format('b(~w)~n', [X]),
X.</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight Prologlang="prolog">?- short_circuit.
a(true) or b(true)
a(true)
Line 3,397:
==> false
 
true.</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Logical '''And''' &amp; '''Or''' operators will not evaluate their right-hand expression if the outcome can be determined from the value of the left-hand expression.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure a(arg)
PrintN(" # Called function a("+Str(arg)+")")
ProcedureReturn arg
Line 3,420:
Next
Next
Input()</langsyntaxhighlight>
{{out}}
<pre>Calculating: x = a(0) And b(0)
Line 3,448:
=={{header|Python}}==
Pythons '''and''' and '''or''' binary, infix, boolean operators will not evaluate their right-hand expression if the outcome can be determined from the value of the left-hand expression.
<langsyntaxhighlight lang="python">>>> def a(answer):
print(" # Called function a(%r) -> %r" % (answer, answer))
return answer
Line 3,487:
# Called function b(True) -> True
Calculating: y = a(i) or b(j)
# Called function a(True) -> True</langsyntaxhighlight>
Pythons if ''expression'' can also be used to the same ends (but probably should not):
<langsyntaxhighlight lang="python">>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False")
Line 3,520:
# Called function b(True) -> True
Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True
# Called function a(True) -> True</langsyntaxhighlight>
 
=={{header|R}}==
The builtins <tt><nowiki>&&</nowiki></tt> and <tt>||</tt> will short circuit:
{{trans|Perl}}
<langsyntaxhighlight lang="r">a <- function(x) {cat("a called\n"); x}
b <- function(x) {cat("b called\n"); x}
 
Line 3,533:
call <- substitute(op(a(x),b(y)), row)
cat(deparse(call), "->", eval(call), "\n\n")
}))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="r">a called
a(1) || b(1) -> TRUE
 
Line 3,561:
 
a called
a(0) && b(0) -> FALSE </langsyntaxhighlight>
Because R waits until function arguments are needed before evaluating them, user-defined functions can also short circuit.
<langsyntaxhighlight lang="r">switchop <- function(s, x, y) {
if(s < 0) x || y
else if (s > 0) x && y
else xor(x, y)
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="r">> switchop(-1, a(1), b(1))
a called
[1] TRUE
Line 3,582:
a called
b called
[1] TRUE</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(define (a x)
(display (~a "a:" x " "))
Line 3,602:
(displayln `(or (a ,x) (b ,y)))
(or (a x) (b y))
(newline))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,626:
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>use MONKEY-SEE-NO-EVAL;
 
sub a ($p) { print 'a'; $p }
Line 3,638:
print "\n";
}
}</langsyntaxhighlight>
{{out}}
<pre>a(1) && b(1): ab
Line 3,653:
language specifications that
<br>short-circuiting is '''not''' supported).
<langsyntaxhighlight lang="rexx">/*REXX programs demonstrates short─circuit evaluation testing (in an IF statement).*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= -2 /*Not specified? Then use the default.*/
Line 3,668:
/*──────────────────────────────────────────────────────────────────────────────────────*/
a: say ' A entered with:' arg(1); return abs( arg(1) // 2) /*1=odd, 0=even */
b: say ' B entered with:' arg(1); return arg(1) < 0 /*1=neg, 0=if not*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,705:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Short-circuit evaluation
 
Line 3,734:
b = t
return b
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,763:
=={{header|Ruby}}==
Binary operators are short-circuiting. Demonstration code:
<langsyntaxhighlight lang="ruby">def a( bool )
puts "a( #{bool} ) called"
bool
Line 3,780:
puts
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,813:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for k = 1 to 2
ao$ = word$("AND,OR",k,",")
print "========= ";ao$;" =============="
Line 3,836:
print chr$(9);"calls func b"
b = t
end function</langsyntaxhighlight>
<pre>========= AND ==============
a(0) AND b(0)
Line 3,862:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">fn a(foo: bool) -> bool {
println!("a");
foo
Line 3,880:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,909:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
a(v:BOOL):BOOL is
#OUT + "executing a\n";
Line 3,934:
#OUT + "F or T = " + x + "\n\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object ShortCircuit {
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
Line 3,953:
println
}
}</langsyntaxhighlight>
{{out}}
<pre>Testing A=false AND B=false -> Called A=false
Line 3,965:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">>(define (a x)
(display "a\n")
x)
Line 3,999:
a
b
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func boolean: a (in boolean: aBool) is func
Line 4,032:
test(TRUE, FALSE);
test(TRUE, TRUE);
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 4,058:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func a(bool) { print 'A'; return bool }
func b(bool) { print 'B'; return bool }
 
Line 4,073:
 
# Test and display
test()</langsyntaxhighlight>
{{out}}
<pre>a(1) && b(1): AB
Line 4,085:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL;
Line 4,137:
TEST;
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,153:
{{works with|GNU Smalltalk}}
The <code>and:</code> <code>or:</code> selectors are shortcircuit selectors but in order to avoid evaluation of the second operand, it must be a block: <code>a and: [ code ]</code> will evaluate the code only if a is true. On the other hand, <code>a and: b</code>, where b is an expression (not a block), behaves like the non-shortcircuit and (&amp;). (Same speech for or |)
<langsyntaxhighlight lang="smalltalk">Smalltalk at: #a put: nil.
Smalltalk at: #b put: nil.
 
Line 4,173:
('true and false = %1' %
{ (a value: true) and: [ b value: false ] })
displayNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 4,179:
 
The test statements below use a pattern constructed from the functions a( ) and b( ) and match it to the null string with deferred evaluation. This idiom allows the functions to self-report the expected short-circuit patterns.
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('a(val)') :(a_end)
a out = 'A '
eq(val,1) :s(return)f(freturn)
Line 4,204:
out = 'F or T: '; null ? *a(0) | *b(1); nl()
out = 'F or F: '; null ? *a(0) | *b(0); nl()
end</langsyntaxhighlight>
{{out}}
<pre>T and T: A B
Line 4,218:
=={{header|Standard ML}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="sml">fun a r = ( print " > function a called\n"; r )
fun b r = ( print " > function b called\n"; r )
 
Line 4,239:
test_this test_and;
print "==== Testing or ====\n";
test_this test_or;</langsyntaxhighlight>
{{out}}
==== Testing and ====
Line 4,268:
Stata always evaluates both arguments of operators & and |. Here is a solution with '''if''' statements.
 
<langsyntaxhighlight lang="stata">function a(x) {
printf(" a")
return(x)
Line 4,291:
printf("\n")
return((x,y))
}</langsyntaxhighlight>
 
'''Example'''
 
<langsyntaxhighlight lang="stata">: call(0,1)
and: a
or: a b
Line 4,309:
+---------+
1 | 1 1 |
+---------+</langsyntaxhighlight>
 
=={{header|Swift}}==
Short circuit operators are <nowiki>&&</nowiki> and ||.
<langsyntaxhighlight lang="swift">func a(v: Bool) -> Bool {
print("a")
return v
Line 4,338:
test(false, true)
test(true, false)
test(true, true)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,372:
=={{header|Tcl}}==
The <code>&&</code> and <code>||</code> in the <code>expr</code> command support short-circuit evaluation. It is recommended that you always put expressions in braces so that and command or variable substitutions are applied at the right time rather than before the expression is evaluated at all. (Indeed, it is recommended that you do that anyway as unbraced expressions cannot be efficiently compiled.)
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc tcl::mathfunc::a boolean {
puts "a($boolean) called"
Line 4,390:
puts ""; # Blank line for clarity
}
}</langsyntaxhighlight>
{{out}}Note that booleans may be written out words or numeric:
<pre>
Line 4,420:
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txr">@(define a (x out))
@ (output)
a (@x) called
Line 4,454:
@(short_circuit_demo "0" "1")
@(short_circuit_demo "1" "0")
@(short_circuit_demo "1" "1")</langsyntaxhighlight>
{{out|Run}}
<pre>$ txr short-circuit-bool.txr
Line 4,488:
The ''&&'' and ''||'' operators use the exit status of each command. The ''true'' and ''false'' commands convert a string to an exit status; our code ''&& x=true || x=false'' converts an exit status to a string.
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">a() {
echo "Called a $1"
"$1"
Line 4,506:
echo " $i || $j is $y"
done
done</langsyntaxhighlight>
The output reveals that <nowiki>&&</nowiki> and || have short-circuit evaluation.
<pre>Called a false
Line 4,531:
==={{header|C Shell}}===
Between commands, ''&&'' and ''||'' have short-circuit evaluation. (The aliases for ''a'' and ''b'' must expand to a single command; these aliases expand to an ''eval'' command.)
<langsyntaxhighlight lang="csh">alias a eval \''echo "Called a \!:1"; "\!:1"'\'
alias b eval \''echo "Called b \!:1"; "\!:1"'\'
 
Line 4,542:
echo " $i || $j is $x"
end
end</langsyntaxhighlight>
Inside expressions, ''&&'' and ''||'' can short circuit some commands, but cannot prevent substitutions.
<langsyntaxhighlight lang="csh"># Succeeds, only prints "ok".
if ( 1 || { echo This command never runs. } ) echo ok
 
Line 4,551:
 
# Prints "error", then "ok".
if ( 1 || `echo error >/dev/stderr` ) echo ok</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
Line 4,587:
Debug.Print
End Sub
</langsyntaxhighlight>{{out}}<pre>=====AND=====
 
a: Onwaar = x
Line 4,605:
=={{header|Visual Basic .NET}}==
{{trans|c++}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function A(v As Boolean) As Boolean
Line 4,633:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>a
Line 4,684:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
*!* Visual FoxPro natively supports short circuit evaluation
CLEAR
Line 4,719:
RETURN v
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,735:
=={{header|Wren}}==
Wren has the '''&&''' and '''||''' short-circuiting operators found in many C family languages.
<langsyntaxhighlight lang="ecmascript">var a = Fn.new { |bool|
System.print(" a called")
return bool
Line 4,756:
a.call(bool[0]) || b.call(bool[1])
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 4,790:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn a(b){self.fcn.println(b); b}
fcn b(b){self.fcn.println(b); b}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits