Short-circuit evaluation: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (→{{header|Wren}}: Changed to Wren S/H) |
|||
(24 intermediate revisions by 16 users not shown) | |||
Line 32:
{{trans|Python}}
<
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)</
{{out}}
Line 73:
Calculating: y = a(i) or b(j)
# Called function a(1B)
</pre>
=={{header|6502 Assembly}}==
There are no built-in booleans but the functionality can be easily implemented with 0 = False and 255 = True.
Source Code for the module:
<syntaxhighlight lang="6502asm">;DEFINE 0 AS FALSE, $FF as true.
False equ 0
True equ 255
Func_A:
;input: accumulator = value to check. 0 = false, nonzero = true.
;output: 0 if false, 255 if true. Also prints the truth value to the screen.
;USAGE: LDA val JSR Func_A
BEQ .falsehood
load16 z_HL,BoolText_A_True ;lda #<BoolText_A_True sta z_L lda #>BoolText_A_True sta z_H
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_A_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_B:
;input: Y = value to check. 0 = false, nonzero = true.
;output: 0 if false, 255 if true. Also prints the truth value to the screen.
;USAGE: LDY val JSR Func_B
TYA
BEQ .falsehood ;return false
load16 z_HL,BoolText_B_True
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_B_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_A_and_B:
;input:
; z_B = input for Func_A
; z_C = input for Func_B
;output:
;0 if false, 255 if true
LDA z_B
jsr Func_A
BEQ .falsehood
LDY z_C
jsr Func_B
BEQ .falsehood
;true
load16 z_HL,BoolText_A_and_B_True
jsr PrintString
jsr NewLine
LDA #True
rts
.falsehood:
load16 z_HL,BoolText_A_and_B_False
jsr PrintString
jsr NewLine
LDA #False
rts
Func_A_or_B:
;input:
; z_B = input for Func_A
; z_C = input for Func_B
;output:
;0 if false, 255 if true
LDA z_B
jsr Func_A
BNE .truth
LDY z_C
jsr Func_B
BNE .truth
;false
load16 z_HL,BoolText_A_or_B_False
jsr PrintString
LDA #False
rts
.truth:
load16 z_HL,BoolText_A_or_B_True
jsr PrintString
LDA #True
rts
BoolText_A_True:
db "A IS TRUE",0
BoolText_A_False:
db "A IS FALSE",0
BoolText_B_True:
db "B IS TRUE",0
BoolText_B_False:
db "B IS FALSE",0
BoolText_A_and_B_True:
db "A AND B IS TRUE",0
BoolText_A_and_B_False:
db "A AND B IS FALSE",0
BoolText_A_or_B_True:
db "A OR B IS TRUE",0
BoolText_A_or_B_False:
db "A OR B IS FALSE",0</syntaxhighlight>
The relevant code for the actual invoking of the functions:
<syntaxhighlight lang="6502asm">lda #True
sta z_B
lda #True
sta z_C
jsr Func_A_and_B
jsr NewLine
jsr Func_A_or_B
jmp *</syntaxhighlight>
And finally the output:
[[https://i.ibb.co/TTJRphL/shortcircuit.png Output image]]
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC a(BYTE x)
PrintF(" a(%B)",x)
RETURN (x)
BYTE FUNC b(BYTE x)
PrintF(" b(%B)",x)
RETURN (x)
PROC Main()
BYTE i,j
FOR i=0 TO 1
DO
FOR j=0 TO 1
DO
PrintF("Calculating %B AND %B: call",i,j)
IF a(i)=1 AND b(j)=1 THEN
FI
PutE()
OD
OD
PutE()
FOR i=0 TO 1
DO
FOR j=0 TO 1
DO
PrintF("Calculating %B OR %B: call",i,j)
IF a(i)=1 OR b(j)=1 THEN
FI
PutE()
OD
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Short-circuit_evaluation.png Screenshot from Atari 8-bit computer]
<pre>
Calculating 0 AND 0: call a(0)
Calculating 0 AND 1: call a(0)
Calculating 1 AND 0: call a(1) b(0)
Calculating 1 AND 1: call a(1) b(1)
Calculating 0 OR 0: call a(0) b(0)
Calculating 0 OR 1: call a(0) b(1)
Calculating 1 OR 0: call a(1)
Calculating 1 OR 1: call a(1)
</pre>
=={{header|Ada}}==
Ada has built-in short-circuit operations '''and then''' and '''or else''':
<
procedure Test_Short_Circuit is
Line 103 ⟶ 281:
end loop;
end loop;
end Test_Short_Circuit;</
{{out|Sample output}}
<pre>
Line 122 ⟶ 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''.
<
OP ORELSE = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ),
ANDTHEN = (BOOL a, PROC BOOL b)BOOL: ( a | b | a );
Line 159 ⟶ 337:
print(("T ANDTHEN T = ", a(TRUE) ANDTHEN (BOOL:b(TRUE)), new line))
)</
{{out}}
<pre>
Line 175 ⟶ 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]}}
<
PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a),
Line 199 ⟶ 377:
END CO
)</
{{out}}
<pre>
Line 214 ⟶ 392:
=={{header|ALGOL W}}==
In Algol W the boolean "and" and "or" operators are short circuit operators.
<
logical procedure a( logical value v ) ; begin write( "a: ", v ); v end ;
Line 228 ⟶ 406:
write( "---" );
end.</
{{out}}
<pre>
Line 255 ⟶ 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)
<
map(test, {|and|, |or|})
Line 308 ⟶ 486:
end map
</syntaxhighlight>
Line 328 ⟶ 506:
{{true, false, false, false}, {true, true, true, false}}
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">a: function [v][
print ["called function A with:" v]
v
]
b: function [v][
print ["called function B with:" v]
v
]
loop @[true false] 'i ->
loop @[true false] 'j ->
print ["\tThe result of A(i) AND B(j) is:" and? -> a i -> b j]
print ""
loop @[true false] 'i ->
loop @[true false] 'j ->
print ["\tThe result of A(i) OR B(j) is:" or? -> a i -> b j]</syntaxhighlight>
{{out}}
<pre>called function A with: true
called function B with: true
The result of A(i) AND B(j) is: true
called function A with: true
called function B with: false
The result of A(i) AND B(j) is: false
called function A with: false
The result of A(i) AND B(j) is: false
called function A with: false
The result of A(i) AND B(j) is: false
called function A with: true
The result of A(i) OR B(j) is: true
called function A with: true
The result of A(i) OR B(j) is: true
called function A with: false
called function B with: true
The result of A(i) OR B(j) is: true
called function A with: false
called function B with: false
The result of A(i) OR B(j) is: false</pre>
=={{header|AutoHotkey}}==
In AutoHotkey, the boolean operators, '''and''', '''or''', and ternaries, short-circuit:
<syntaxhighlight lang="autohotkey">i = 1
j = 1
x := a(i) and b(j)
Line 346 ⟶ 570:
MsgBox, b() was called with the parameter "%p%".
Return, p
}</
=={{header|AWK}}==
Short-circuit evalation is done in logical AND (&&) and logical OR (||) operators:
<
BEGIN {
print (a(1) && b(1))
Line 366 ⟶ 590:
print " y:"y
return y
}</
{{out}}
<pre>
Line 382 ⟶ 606:
=={{header|Axe}}==
<
TEST(0,1)
TEST(1,0)
Line 403 ⟶ 627:
Lbl B
r₁
Return</
=={{header|
==={{header|BaCon}}===
BaCon supports short-circuit evaluation.
<
FUNCTION a(f)
PRINT "FUNCTION a"
Line 433 ⟶ 658:
PRINT "TRUE or FALSE"
y = a(TRUE) OR b(FALSE)
PRINT y</
{{out}}
Line 454 ⟶ 679:
=={{header|Batch File}}==
{{trans|Liberty BASIC}}
<
%=== I will instead use 1 as true and 0 as false. ===%
Line 500 ⟶ 725:
echo. calls func b
set bool_b=%1
goto :EOF</
{{Out}}
<pre>AND
Line 537 ⟶ 762:
=={{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.
<
FOR i% = TRUE TO FALSE
FOR j% = TRUE TO FALSE
Line 564 ⟶ 789:
DEFFNboolstring(bool%)
IF bool%=0 THEN ="FALSE" ELSE="TRUE"</
This gives the results shown below:
<pre>For x=a(TRUE) AND b(TRUE)
Line 594 ⟶ 819:
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.
<
& (b=.out$"I'm b"&!!arg)
& (false==~)
Line 622 ⟶ 847:
& done
);
</syntaxhighlight>
Output:
<pre>Testing false AND false
Line 647 ⟶ 872:
=={{header|C}}==
Boolean operators <nowiki>&&</nowiki> and || are shortcircuit operators.
<
#include <stdbool.h>
Line 678 ⟶ 903:
return 0;
}</
=={{header|C sharp|C#}}==
<
class Program
Line 710 ⟶ 935:
}
}
}</
{{out}}
<syntaxhighlight lang="text">a
False and False = False
Line 738 ⟶ 963:
a
True or True = True</
=={{header|C++}}==
Just like C, boolean operators <nowiki>&&</nowiki> and || are shortcircuit operators.
<
bool a(bool in)
Line 768 ⟶ 993:
test(true, true);
return 0;
}</
{{out}}
<pre>a
Line 793 ⟶ 1,018:
=={{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).
<
(b [bool] (print "(b)") bool)]
(doseq [i [true false] j [true false]]
Line 799 ⟶ 1,024:
(println (or (a i) (b j)))
(print i "AND" j " = ")
(println (and (a i) (b j)))))</
{{out}}
<pre>true OR true = (a)true
Line 811 ⟶ 1,036:
=={{header|Common Lisp}}==
<
(print 'a)
F )
Line 823 ⟶ 1,048:
(and (a (car x)) (b (car(cdr x))))
(format t "~%(or ~S)" x)
(or (a (car x)) (b (car(cdr x)))))</
{{out}}
(and (NIL NIL))
Line 848 ⟶ 1,073:
=={{header|D}}==
{{trans|Python}}
<
T a(T)(T answer) {
Line 868 ⟶ 1,093:
immutable r2 = a(x) || b(y);
}
}</
{{out}}
<pre>
Line 897 ⟶ 1,122:
=={{header|Delphi}}==
Delphi supports short circuit evaluation by default. It can be turned off using the {$BOOLEVAL OFF} compiler directive.
<
{$APPTYPE CONSOLE}
Line 928 ⟶ 1,153:
end;
end;
end.</
=={{header|Dyalect}}==
Line 934 ⟶ 1,159:
{{trans|Swift}}
<
print(nameof(a), terminator: "")
return v
Line 959 ⟶ 1,184:
testMe(false, true)
testMe(true, false)
testMe(true, true)</
{{out}}
Line 993 ⟶ 1,218:
=={{header|E}}==
E defines <code>&&</code> and <code>||</code> in the usual short-circuiting fashion.
<
def b(v) { println("b"); return v }
def x := a(i) && b(j)
def y := b(i) || b(j)</
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.
<
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|EasyLang}}==
<syntaxhighlight lang=easylang>
func a x .
print "->a: " & x
return x
.
func b x .
print "->b: " & x
return x
.
print "1 and 1"
if a 1 = 1 and b 1 = 1
print "-> true"
.
print ""
print "1 or 1"
if a 1 = 1 or b 1 = 1
print "-> true"
.
print ""
print "0 and 1"
if a 0 = 1 and b 1 = 1
print "-> true"
.
print ""
print "0 or 1"
if a 0 = 1 or b 1 = 1
print "-> true"
.
</syntaxhighlight>
=={{header|Ecstasy}}==
Similar to Java, Ecstasy uses the <span style="background-color: #e5e4e2"> && </tt></span> and <span style="background-color: #e5e4e2"><tt> || </tt></span> operators for short-circuiting logic, and <span style="background-color: #e5e4e2"><tt> & </tt></span> and <span style="background-color: #e5e4e2"><tt> | </tt></span> are the normal (non-short-circuiting) forms.
<syntaxhighlight lang="java">
module test {
@Inject Console console;
static Boolean show(String name, Boolean value) {
console.print($"{name}()={value}");
return value;
}
void run() {
val a = show("a", _);
val b = show("b", _);
for (Boolean v1 : False..True) {
for (Boolean v2 : False..True) {
console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}");
console.print();
console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}");
console.print();
}
}
}
}
</syntaxhighlight>
{{out}}
<pre>
a()=False
a(False) && b(False) == False
a()=False
b()=False
a(False) || b(False) == False
a()=False
a(False) && b(True) == False
a()=False
b()=True
a(False) || b(True) == True
a()=True
b()=False
a(True) && b(False) == False
a()=True
a(True) || b(False) == True
a()=True
b()=True
a(True) && b(True) == True
a()=True
a(True) || b(True) == True
</pre>
=={{header|Elena}}==
ELENA
<
import extensions;
Func<bool, bool> a = (bool x){ console.writeLine
Func<bool, bool> b = (bool x){ console.writeLine
const bool[] boolValues = new bool[]{ false, true };
Line 1,015 ⟶ 1,330:
public program()
{
boolValues.forEach::(bool i)
{
boolValues.forEach::(bool j)
{
console.printLine(i," and ",j," = ",a(i) && b(j));
Line 1,026 ⟶ 1,341:
}
}
}</
{{out}}
<pre>
Line 1,059 ⟶ 1,374:
=={{header|Elixir}}==
<
defp a(bool) do
IO.puts "a( #{bool} ) called"
Line 1,080 ⟶ 1,395:
end
Short_circuit.task</
{{out}}
Line 1,114 ⟶ 1,429:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( short_circuit_evaluation ).
Line 1,137 ⟶ 1,452:
io:fwrite( "~p orelse ~p~n", [Boolean1, Boolean2] ),
io:fwrite( "=> ~p~n", [a(Boolean1) orelse b(Boolean2)] ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,172 ⟶ 1,487:
=={{header|F_Sharp|F#}}==
<
let b (x : bool) = printf "(b)"; x
Line 1,178 ⟶ 1,493:
|> 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)))</
Output
<pre>(a)(b)true AND true = true
Line 1,191 ⟶ 1,506:
=={{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.
<
IN: rosetta-code.short-circuit
Line 1,204 ⟶ 1,519:
"t || f = " write { [ t a ] [ f b ] } || .
"t && t = " write { [ t a ] [ t b ] } && .
"t || t = " write { [ t a ] [ t b ] } || .</
{{out}}
<pre>
Line 1,218 ⟶ 1,533:
=={{header|Fantom}}==
<
{
static Bool a (Bool value)
Line 1,245 ⟶ 1,560:
}
}
}</
{{out}}
<pre>
Line 1,271 ⟶ 1,586:
=={{header|Forth}}==
<
: ENDIF postpone THEN ; immediate
Line 1,298 ⟶ 1,613:
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 ;</
{{out}}
<pre>A=true B=true ANDIF=true
Line 1,312 ⟶ 1,627:
{{works with|Fortran|90 and later}}
Using an <code>IF .. THEN .. ELSE</code> construct
<
implicit none
Line 1,362 ⟶ 1,677:
write(*, "(a,l1,a)") "Called function b(", value, ")"
end function
end program</
{{out}}
<pre>Calculating x = a(F) and b(F)
Line 1,401 ⟶ 1,716:
=={{header|FreeBASIC}}==
<
Function a(p As Boolean) As Boolean
Line 1,429 ⟶ 1,744:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,451 ⟶ 1,766:
=={{header|Fōrmulæ}}==
'''Solution'''
[[File:Fōrmulæ - Short-circuit evaluation 01.png]]
[[File:Fōrmulæ - Short-circuit evaluation 02.png]]
=={{header|Go}}==
Short circuit operators are <nowiki>&&</nowiki> and ||.
<
import "fmt"
Line 1,490 ⟶ 1,807:
test(true, false)
test(true, true)
}</
{{out}}
<pre>Testing a(false) && b(false)
Line 1,522 ⟶ 1,839:
=={{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.
<
def g = { printf ('%5d ', it); it > 50 }
Line 1,536 ⟶ 1,853:
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert g(200) || f('sss')</
{{out}}
<pre>bitwise
Line 1,551 ⟶ 1,868:
=={{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]]:
<
import Prelude hiding ((&&), (||))
Line 1,568 ⟶ 1,885:
main = mapM_ print ( [ a p || b q | p <- [False, True], q <- [False, True] ]
++ [ a p && b q | p <- [False, True], q <- [False, True] ])</
{{out}}
<pre>
Line 1,593 ⟶ 1,910:
</pre>
One can force the right-hand arguemnt to be evaluated first be using the alternate definitions:
<
False && True = False
_ && _ = True
Line 1,599 ⟶ 1,916:
_ || True = True
True || False = True
_ || _ = False</
{{out}}
<pre>
Line 1,624 ⟶ 1,941:
</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:
<
False -> False
_ -> case q of
Line 1,634 ⟶ 1,951:
_ -> case q of
True -> True
_ -> False</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,645 ⟶ 1,962:
* 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).
<
&trace := -1 # ensures functions print their names
Line 1,663 ⟶ 1,980:
procedure false() #: fails always
fail # for clarity but not needed as running into end has the same effect
end</
Sample output for a single case:<pre>i,j := procedure true, procedure false
i & j:
Line 1,674 ⟶ 1,991:
Shortcircuit.icn: 16 | true returned &null
i,j := procedure true, procedure true</pre>
=={{header|Insitux}}==
{{trans|Clojure}}
<syntaxhighlight lang="insitux">
(let a (fn (print-str "a ") %)
b (fn (print-str "b ") %)
f (pad-right " " 6))
(for i [true false] j [true false]
(print-str (f i) "OR " (f j) " = ")
(print (or (a i) (b j)))
(print-str (f i) "AND " (f j) " = ")
(print (and (a i) (b j))))
</syntaxhighlight>
{{out}}
<pre>
true OR true = a true
true AND true = a b true
true OR false = a true
true AND false = a b false
false OR true = a b true
false AND true = a false
false OR false = a b false
false AND false = a false
</pre>
=={{header|Io}}==
{{trans|Ruby}}
<
writeln("a(#{bool}) called." interpolate)
bool
Line 1,695 ⟶ 2,037:
writeln
)
)</
{{output}}
<pre>a(true) called.
Line 1,727 ⟶ 2,069:
=={{header|J}}==
See the J wiki entry on [[j:Essays/Short Circuit Boolean|short circuit booleans]].
<
A=: 'A ' labeled
B=: 'B ' labeled
and=: ^:
or=: 2 :'u^:(-.@v)'</
{{out|Example}}
<
B 1
A 1
Line 1,746 ⟶ 2,088:
B 0
A 0
0</
Note that J evaluates right-to-left.
Line 1,753 ⟶ 2,095:
=={{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>.
<
public static void main(String[] args){
System.out.println("F and F = " + (a(false) && b(false)) + "\n");
Line 1,777 ⟶ 2,119:
return b;
}
}</
{{out}}
<pre>a
Line 1,811 ⟶ 2,153:
Short-circuiting evaluation of boolean expressions has been the default since the first versions of JavaScript.
<
'use strict';
Line 1,832 ⟶ 2,174:
return [x, y, z];
})();</
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 1,848 ⟶ 2,190:
=={{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'.
<
def b(y): " b(\(y))" | stderr | y;
Line 1,855 ⟶ 2,197:
"or:", (a(true) or b(true)),
"and:", (a(false) and b(true)),
"or:", (a(false) or b(true))</
{{out}}
<
and:
" a(true)"
Line 1,871 ⟶ 2,213:
" a(false)"
" b(true)"
true</
=={{header|Julia}}==
Julia does have short-circuit evaluation, which works just as you expect it to:
<
b(x) = (println("\t# Called b($x)"); return x)
Line 1,884 ⟶ 2,226:
println("\nCalculating: y = a($i) || b($j)"); y = a(i) || b(j)
println("\tResult: y = $y")
end</
{{out}}
<pre>Calculating: x = a(true) && b(true)
Line 1,923 ⟶ 2,265:
=={{header|Kotlin}}==
<
fun a(v: Boolean): Boolean {
Line 1,944 ⟶ 2,286:
println()
}
}</
{{out}}
Line 1,976 ⟶ 2,318:
Short-circuiting evaluation of boolean expressions has been the default since the first versions of lambdatalk.
<
{def A {lambda {:bool} :bool}} -> A
{def B {lambda {:bool} :bool}} -> B
Line 1,989 ⟶ 2,331:
{or {A false} {B true}} -> true
{or {A false} {B false}} -> false
</syntaxhighlight>
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.
<
{def fib
Line 2,024 ⟶ 2,366:
{{P.right {when}}} -> 832040 // after choice using {}
</syntaxhighlight>
=={{header|Liberty BASIC}}==
LB does not have short-circuit evaluation. Implemented with IFs.
<
for i = 0 to 1
for j = 0 to 1
Line 2,062 ⟶ 2,404:
print ,"calls func b"
b = t
end function </
{{out}}
<pre>AND
Line 2,098 ⟶ 2,440:
=={{header|LiveCode}}==
Livecode uses short-circuit evaluation.
<
function a bool
put "a called with" && bool & cr after outcome
Line 2,121 ⟶ 2,463:
end repeat
put outcome
end mouseUp</
=={{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.
<
(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y < 3])</
=={{header|Lua}}==
<
print "Function a(i) called."
return i
Line 2,145 ⟶ 2,487:
i = false
x = a(i) and b(i); print ""
y = a(i) or b(i)</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Short_circuit_evaluation {
function a(a as boolean) {
=a
doc$<=format$(" Called function a({0}) -> {0}", a)+{
}
}
function b(b as boolean) {
=b
doc$<=format$(" Called function b({0}) -> {0}", b)+{
}
}
boolean T=true, F, iv, jv
variant L=(F, T), i, j
i=each(L)
global doc$ : document doc$
while i
j=each(L)
while j
(iv, jv)=(array(i), array(j))
doc$<=format$("Calculating x = a({0}) and b({1}) -> {2}", iv, jv, iv and jv)+{
}
x=if(a(iv)->b(jv), F)
doc$<=format$("x={0}", x)+{
}+ format$("Calculating y = a({0}) or b({1}) -> {2}", iv, jv, iv or jv)+{
}
y=if(a(iv)->T, b(jv))
doc$<=format$("y={0}", y)+{
}
end while
end while
clipboard doc$
report doc$
}
Short_circuit_evaluation
</syntaxhighlight>
{{out}}
<pre>
Calculating x = a(False) and b(False) -> False
Called function a(False) -> False
x=False
Calculating y = a(False) or b(False) -> False
Called function a(False) -> False
Called function b(False) -> False
y=False
Calculating x = a(False) and b(True) -> False
Called function a(False) -> False
x=False
Calculating y = a(False) or b(True) -> True
Called function a(False) -> False
Called function b(True) -> True
y=True
Calculating x = a(True) and b(False) -> False
Called function a(True) -> True
Called function b(False) -> False
x=False
Calculating y = a(True) or b(False) -> True
Called function a(True) -> True
y=True
Calculating x = a(True) and b(True) -> True
Called function a(True) -> True
Called function b(True) -> True
x=True
Calculating y = a(True) or b(True) -> True
Called function a(True) -> True
y=True
</pre>
=={{header|Maple}}==
Built-in short circuit evaluation
<
printf("a is called->%s\n", bool):
return bool:
Line 2,164 ⟶ 2,580:
y := a(i) or b(j):
od:
od:</
{{Out|Output}}
<pre>calculating x := a(i) and b(j)
Line 2,187 ⟶ 2,603:
b is called->false</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has built-in short-circuit evaluation of logical expressions.
<
b[in_] := (Print["b"]; in)
a[False] && b[True]
a[True] || b[False]</
Evaluation of the preceding code gives:
<pre>a
False
a
True</pre>
Whereas evaluating this:
<
Gives:
<pre>a
b
False</pre>
=={{header|MATLAB}} / {{header|Octave}}==
Short-circuit evalation is done in logical AND (&&) and logical OR (||) operators:
<
printf('a: %i\n',x);
end;
Line 2,223 ⟶ 2,633:
a(0) && b(1)
a(1) || b(1)
a(0) || b(1)</
{{out}}
<
a: 1
b: 1
Line 2,234 ⟶ 2,644:
> a(0) || b(1);
a: 0
b: 1</
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,278 ⟶ 2,688:
Print(TRUE,FALSE);
ReadChar
END ShortCircuit.</
=={{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.
<
WRITE !,?10,$STACK($STACK,"PLACE")
QUIT IN
Line 2,303 ⟶ 2,713:
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
KILL Z
QUIT</
{{out}}
<pre>USER>D SSEVAL3^ROSETTA
Line 2,326 ⟶ 2,736:
=={{header|Nanoquery}}==
Nanoquery does not short-circuit by default, so short-circuit logic functions have been implemented by nested ifs.
<
global a
global b
Line 2,372 ⟶ 2,782:
println "T and T = " + short_and(true, true) + "\n"
println "T or T = " + short_or(true, true) + "\n"</
{{out}}
<pre>a called.
Line 2,404 ⟶ 2,814:
=={{header|Nemerle}}==
<
class ShortCircuit
Line 2,434 ⟶ 2,844:
WriteLine("False || False: {0}", a(f) || b(f));
}
}</
{{out}}
<syntaxhighlight lang="text">a
b
True && True : True
Line 2,455 ⟶ 2,865:
a
b
False || False: False</
=={{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>.
<
options replace format comments java crossref symbols nobinary
Line 2,489 ⟶ 2,899:
Say '--b returns' state
Return state
</syntaxhighlight>
{{out}}
<pre>
Line 2,512 ⟶ 2,922:
=={{header|Nim}}==
Nim produces code which uses short-circuit evaluation.
<
echo "a called"
result = x
Line 2,521 ⟶ 2,931:
let x = a(false) and b(true) # echoes "a called"
let y = a(true) or b(true) # echoes "a called"</
=={{header|Objeck}}==
In Objeck the Boolean operators <code>&</code> and <code>|</code> short circuit.
<
function : a(a : Bool) ~ Bool {
"a"->PrintLine();
Line 2,557 ⟶ 2,967:
"T or T = {$result}"->PrintLine();
}
}</
=={{header|OCaml}}==
<
let b r = print_endline " > function b called"; r
Line 2,583 ⟶ 2,993:
print_endline "==== Testing or ====";
test_this test_or;
;;</
{{out}}
==== Testing and ====
Line 2,609 ⟶ 3,019:
=={{header|Ol}}==
<
(define (a x)
(print " (a) => " x)
Line 2,635 ⟶ 3,045:
'(#t #t #f #f)
'(#t #f #t #f))
</syntaxhighlight>
{{Out}}
<pre>
Line 2,673 ⟶ 3,083:
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).
<
Say 'Version='v
If a() | b() Then Say 'a and b are true'
Line 2,688 ⟶ 3,098:
a: Say 'a returns .true'; Return .true
b: Say 'b returns 1'; Return 1
</syntaxhighlight>
{{out}}
<pre>Version=REXX-ooRexx_4.2.0(MT)_32-bit 6.04 22 Feb 2014
Line 2,708 ⟶ 3,118:
=={{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.
<
fun {A Answer}
AnswerS = {Value.toVirtualString Answer 1 1}
Line 2,732 ⟶ 3,142:
Y = {A I} orelse {B J}
end
end</
{{out}}
<
% Called function {A false} -> false
Calculating: Y = {A I} orelse {B J}
Line 2,756 ⟶ 3,166:
% Called function {B true} -> true
Calculating: Y = {A I} orelse {B J}
% Called function {A true} -> true</
=={{header|PARI/GP}}==
Note that <code>|</code> and <code>&</code> are deprecated versions of the GP short-circuit operators.
<
print(a"("n")");
a
Line 2,773 ⟶ 3,183:
and(A,B)={
a(A) && b(B)
};</
=={{header|Pascal}}==
===Standard Pascal===
Standard Pascal doesn't have native short-circuit evaluation.
<
function a(value: boolean): boolean;
Line 2,818 ⟶ 3,228:
scandor(true, false);
scandor(true, true);
end.</
===Turbo Pascal===
Turbo Pascal allows short circuit evaluation with a compiler switch:
<
function a(value: boolean): boolean;
Line 2,853 ⟶ 3,263:
scandor(true, false);
scandor(true, true);
end.</
===Extended Pascal===
The extended Pascal standard introduces the operators <code>and_then</code> and <code>or_else</code> for short-circuit evaluation.
<
function a(value: boolean): boolean;
Line 2,886 ⟶ 3,296:
scandor(true, false);
scandor(true, true);
end.</
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.
<
sub b { print 'B'; return $_[0] }
Line 2,904 ⟶ 3,314:
# Test and display
test();</
{{out}}
<pre>a(1) && b(1): AB
Line 2,916 ⟶ 3,326:
=={{header|Phix}}==
In Phix all expressions are short circuited
<!--<syntaxhighlight lang="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>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"b "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">z</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a(%d) and b(%d) "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" => %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a(%d) or b(%d) "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" => %d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">or</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,952 ⟶ 3,366:
=={{header|PicoLisp}}==
<
(msg 'a)
F )
Line 2,965 ⟶ 3,379:
(println I Op J '-> (Op (a I) (b J))) ) )
'(NIL NIL T T)
'(NIL T NIL T) )</
{{out}}
<pre>a
Line 2,989 ⟶ 3,403:
=={{header|Pike}}==
<
{
write(" a\n");
Line 3,008 ⟶ 3,422:
write(" %d || %d\n", @args);
a(args[0]) || b(args[1]);
}</
{{out}}
<pre>
Line 3,034 ⟶ 3,448:
=={{header|PL/I}}==
<
procedure options (main);
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
Line 3,068 ⟶ 3,482:
end;
end;
end short_circuit_evaluation;</
{{out|Results}}
<pre>
Line 3,106 ⟶ 3,520:
=={{header|PowerShell}}==
PowerShell handles this natively.
<
function a ( [boolean]$J ) { return $J }
Line 3,138 ⟶ 3,552:
( a $True ) -and ( b $False )
( a $True ) -and ( b $True )
} | Select TotalMilliseconds</
{{out}}
<pre>True
Line 3,157 ⟶ 3,571:
Prolog has not functions but predicats succeed of fail.
Tested with SWI-Prolog. Should work with other dialects.
<
( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl,
Line 3,182 ⟶ 3,596:
b(X) :-
format('b(~w)~n', [X]),
X.</
{{out}}
<
a(true) or b(true)
a(true)
Line 3,221 ⟶ 3,635:
==> false
true.</
=={{header|PureBasic}}==
Logical '''And''' & '''Or''' operators will not evaluate their right-hand expression if the outcome can be determined from the value of the left-hand expression.
<
PrintN(" # Called function a("+Str(arg)+")")
ProcedureReturn arg
Line 3,244 ⟶ 3,658:
Next
Next
Input()</
{{out}}
<pre>Calculating: x = a(0) And b(0)
Line 3,272 ⟶ 3,686:
=={{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.
<
print(" # Called function a(%r) -> %r" % (answer, answer))
return answer
Line 3,311 ⟶ 3,725:
# Called function b(True) -> True
Calculating: y = a(i) or b(j)
# Called function a(True) -> True</
Pythons if ''expression'' can also be used to the same ends (but probably should not):
<
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False")
Line 3,344 ⟶ 3,758:
# 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</
=={{header|Quackery}}==
Quackery does not include short-circuit evaluation, but it can be added by use of meta-control flow words (words wrapped in reverse brackets such as <code>]done[</code>.) For details see: [https://github.com/GordonCharlton/Quackery/blob/main/The%20Book%20of%20Quackery.pdf The Book of Quackery]
The short-circuit evaluation words <code>SC-and</code> and <code>SC-or</code> defined here are used thus: <code>[ a 1 SC-and b ]</code> and <code>[ a 1 SC-or b ]</code>. These presumes that the arguments to <code>a</code> and <code>b</code> are on the stack in the order <code>j i</code>.
The <code>1</code> preceding the word is required to indicate the number of arguments that <code>b</code> would consume from the stack if it were evaluated.
Extending the task to three functions, the third, <code>c</code> also consuming one argument <code>k</code> and returning a boolean, present on the stack underneath <code>j</code> and <code>i</code> would lead to the code <code>[ a 2 SC-and b 1 SC-and c ]</code> and <code>[ a 2 SC-or b 1 SC-or c ]</code>, where the <code>2</code> is the sum of the number of arguments consumed by <code>b</code> and <code>c</code>, and the <code>1</code> is the number of arguments consumed by <code>c</code>.
<code>SC-and</code> and <code>SC-or</code> can both be used in a single short-circuit evaluation nest with three or more functions. Evaluation is strictly left to right.
Quackery does not have variables, so no assignment is shown here. Words (functions) leave their results on the stack. If desired results can be moved to ancillary stacks, which include standing-in for variables amongst their functionality.
<syntaxhighlight lang="Quackery">
[ say "evaluating "
]this[ echo cr ] is ident ( --> )
[ iff say "true"
else say "false" ] is echobool ( b --> )
[ swap iff drop done
times drop
false ]done[ ] is SC-and ( b n --> )
[ swap not iff drop done
times drop
true ]done[ ] is SC-or ( b n --> )
[ ident
2 times not ] is a ( b --> b )
[ ident
4 times not ] is b ( b --> b )
[ say "i = "
dup echobool
say " AND j = "
dup echobool
cr
[ a 1 SC-and b ]
say "result is "
echobool cr cr ] is AND-demo ( --> )
[ say "i = "
dup echobool
say " OR j = "
dup echobool
cr
[ a 1 SC-or b ]
say "result is "
echobool
cr cr ] is OR-demo ( --> )
true true AND-demo
true false AND-demo
false true AND-demo
false false AND-demo
cr
true true OR-demo
true false OR-demo
false true OR-demo
false false OR-demo</syntaxhighlight>
{{out}}
<pre>i = true AND j = true
evaluating a
evaluating b
result is true
i = false AND j = false
evaluating a
result is false
i = true AND j = true
evaluating a
evaluating b
result is false
i = false AND j = false
evaluating a
result is false
i = true OR j = true
evaluating a
result is true
i = false OR j = false
evaluating a
evaluating b
result is true
i = true OR j = true
evaluating a
result is true
i = false OR j = false
evaluating a
evaluating b
result is false</pre>
=={{header|R}}==
The builtins <tt><nowiki>&&</nowiki></tt> and <tt>||</tt> will short circuit:
{{trans|Perl}}
<
b <- function(x) {cat("b called\n"); x}
Line 3,357 ⟶ 3,875:
call <- substitute(op(a(x),b(y)), row)
cat(deparse(call), "->", eval(call), "\n\n")
}))</
{{out}}
<
a(1) || b(1) -> TRUE
Line 3,385 ⟶ 3,903:
a called
a(0) && b(0) -> FALSE </
Because R waits until function arguments are needed before evaluating them, user-defined functions can also short circuit.
<
if(s < 0) x || y
else if (s > 0) x && y
else xor(x, y)
}</
{{out}}
<
a called
[1] TRUE
Line 3,406 ⟶ 3,924:
a called
b called
[1] TRUE</
=={{header|Racket}}==
<
(define (a x)
(display (~a "a:" x " "))
Line 3,426 ⟶ 3,944:
(displayln `(or (a ,x) (b ,y)))
(or (a x) (b y))
(newline))</
{{out}}
<pre>
Line 3,450 ⟶ 3,968:
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku"
sub a ($p) { print 'a'; $p }
Line 3,462 ⟶ 3,980:
print "\n";
}
}</
{{out}}
<pre>a(1) && b(1): ab
Line 3,477 ⟶ 3,995:
language specifications that
<br>short-circuiting is '''not''' supported).
<
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= -2 /*Not specified? Then use the default.*/
Line 3,492 ⟶ 4,010:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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*/</
{{out|output|text= when using the default inputs:}}
<pre>
Line 3,529 ⟶ 4,047:
=={{header|Ring}}==
<
# Project : Short-circuit evaluation
Line 3,558 ⟶ 4,076:
b = t
return b
</syntaxhighlight>
Output:
<pre>
Line 3,587 ⟶ 4,105:
=={{header|Ruby}}==
Binary operators are short-circuiting. Demonstration code:
<
puts "a( #{bool} ) called"
bool
Line 3,604 ⟶ 4,122:
puts
end
end</
{{out}}
<pre>
Line 3,637 ⟶ 4,155:
=={{header|Run BASIC}}==
<
ao$ = word$("AND,OR",k,",")
print "========= ";ao$;" =============="
Line 3,660 ⟶ 4,178:
print chr$(9);"calls func b"
b = t
end function</
<pre>========= AND ==============
a(0) AND b(0)
Line 3,686 ⟶ 4,204:
=={{header|Rust}}==
<
println!("a");
foo
Line 3,704 ⟶ 4,222:
}
}
}</
{{out}}
<pre>
Line 3,733 ⟶ 4,251:
=={{header|Sather}}==
<
a(v:BOOL):BOOL is
#OUT + "executing a\n";
Line 3,758 ⟶ 4,276:
#OUT + "F or T = " + x + "\n\n";
end;
end;</
=={{header|Scala}}==
<
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
Line 3,777 ⟶ 4,295:
println
}
}</
{{out}}
<pre>Testing A=false AND B=false -> Called A=false
Line 3,789 ⟶ 4,307:
=={{header|Scheme}}==
<
(display "a\n")
x)
Line 3,823 ⟶ 4,341:
a
b
</syntaxhighlight>
=={{header|Seed7}}==
<
const func boolean: a (in boolean: aBool) is func
Line 3,856 ⟶ 4,374:
test(TRUE, FALSE);
test(TRUE, TRUE);
end func;</
{{out}}
<pre>
Line 3,882 ⟶ 4,400:
=={{header|Sidef}}==
<
func b(bool) { print 'B'; return bool }
Line 3,897 ⟶ 4,415:
# Test and display
test()</
{{out}}
<pre>a(1) && b(1): AB
Line 3,909 ⟶ 4,427:
=={{header|Simula}}==
<
BOOLEAN PROCEDURE A(BOOL); BOOLEAN BOOL;
Line 3,961 ⟶ 4,479:
TEST;
END.
</syntaxhighlight>
{{out}}
<pre>
Line 3,977 ⟶ 4,495:
{{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 (&). (Same speech for or |)
<
Smalltalk at: #b put: nil.
Line 3,997 ⟶ 4,515:
('true and false = %1' %
{ (a value: true) and: [ b value: false ] })
displayNl.</
=={{header|SNOBOL4}}==
Line 4,003 ⟶ 4,521:
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.
<
a out = 'A '
eq(val,1) :s(return)f(freturn)
Line 4,028 ⟶ 4,546:
out = 'F or T: '; null ? *a(0) | *b(1); nl()
out = 'F or F: '; null ? *a(0) | *b(0); nl()
end</
{{out}}
<pre>T and T: A B
Line 4,042 ⟶ 4,560:
=={{header|Standard ML}}==
{{trans|OCaml}}
<
fun b r = ( print " > function b called\n"; r )
Line 4,063 ⟶ 4,581:
test_this test_and;
print "==== Testing or ====\n";
test_this test_or;</
{{out}}
==== Testing and ====
Line 4,092 ⟶ 4,610:
Stata always evaluates both arguments of operators & and |. Here is a solution with '''if''' statements.
<
printf(" a")
return(x)
Line 4,115 ⟶ 4,633:
printf("\n")
return((x,y))
}</
'''Example'''
<
and: a
or: a b
Line 4,133 ⟶ 4,651:
+---------+
1 | 1 1 |
+---------+</
=={{header|Swift}}==
Short circuit operators are <nowiki>&&</nowiki> and ||.
<
print("a")
return v
Line 4,162 ⟶ 4,680:
test(false, true)
test(true, false)
test(true, true)</
{{out}}
<pre>
Line 4,196 ⟶ 4,714:
=={{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.)
<
proc tcl::mathfunc::a boolean {
puts "a($boolean) called"
Line 4,214 ⟶ 4,732:
puts ""; # Blank line for clarity
}
}</
{{out}}Note that booleans may be written out words or numeric:
<pre>
Line 4,244 ⟶ 4,762:
=={{header|TXR}}==
<
@ (output)
a (@x) called
Line 4,278 ⟶ 4,796:
@(short_circuit_demo "0" "1")
@(short_circuit_demo "1" "0")
@(short_circuit_demo "1" "1")</
{{out|Run}}
<pre>$ txr short-circuit-bool.txr
Line 4,312 ⟶ 4,830:
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}}
<
echo "Called a $1"
"$1"
Line 4,330 ⟶ 4,848:
echo " $i || $j is $y"
done
done</
The output reveals that <nowiki>&&</nowiki> and || have short-circuit evaluation.
<pre>Called a false
Line 4,355 ⟶ 4,873:
==={{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.)
<
alias b eval \''echo "Called b \!:1"; "\!:1"'\'
Line 4,366 ⟶ 4,884:
echo " $i || $j is $x"
end
end</
Inside expressions, ''&&'' and ''||'' can short circuit some commands, but cannot prevent substitutions.
<
if ( 1 || { echo This command never runs. } ) echo ok
Line 4,375 ⟶ 4,893:
# Prints "error", then "ok".
if ( 1 || `echo error >/dev/stderr` ) echo ok</
=={{header|VBA}}==
<
Debug.Print "a: "; i = 1,
a = i
Line 4,411 ⟶ 4,929:
Debug.Print
End Sub
</
a: Onwaar = x
Line 4,429 ⟶ 4,947:
=={{header|Visual Basic .NET}}==
{{trans|c++}}
<
Function A(v As Boolean) As Boolean
Line 4,457 ⟶ 4,975:
End Sub
End Module</
{{out}}
<pre>a
Line 4,508 ⟶ 5,026:
=={{header|Visual FoxPro}}==
<
*!* Visual FoxPro natively supports short circuit evaluation
CLEAR
Line 4,543 ⟶ 5,061:
RETURN v
ENDFUNC
</syntaxhighlight>
{{out}}
<pre>
Line 4,555 ⟶ 5,073:
T F OR T a()
T T OR T a()
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
fn main() {
test_me(false, false)
test_me(false, true)
test_me(true, false)
test_me(true, true)
}
fn a(v bool) bool {
print("a")
return v
}
fn b(v bool) bool {
print("b")
return v
}
fn test_me(i bool, j bool) {
println("Testing a(${i}) && b(${j})")
print("Trace: ")
println("\nResult: ${a(i) && b(j)}")
println("Testing a(${i})} || b(${j})")
print("Trace: ")
println("\nResult: ${a(i) || b(j)}")
println("")
}
</syntaxhighlight>
{{out}}
<pre>
Testing a(false) && b(false)
Trace: a
Result: false
Testing a(false)} || b(false)
Trace: ab
Result: false
Testing a(false) && b(true)
Trace: a
Result: false
Testing a(false)} || b(true)
Trace: ab
Result: true
Testing a(true) && b(false)
Trace: ab
Result: false
Testing a(true)} || b(false)
Trace: a
Result: true
Testing a(true) && b(true)
Trace: ab
Result: true
Testing a(true)} || b(true)
Trace: a
Result: true
</pre>
=={{header|Wren}}==
Wren has the '''&&''' and '''||''' short-circuiting operators found in many C family languages.
<
System.print(" a called")
return bool
Line 4,580 ⟶ 5,160:
a.call(bool[0]) || b.call(bool[1])
System.print()
}</
{{out}}
Line 4,614 ⟶ 5,194:
=={{header|zkl}}==
<
fcn b(b){self.fcn.println(b); b}</
{{out}}
<pre>
|