all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

View file

@ -0,0 +1,18 @@
{{Control Structures}}
Assume functions <math>a</math> and <math>b</math> return boolean values, and further, the execution of function <math>b</math> takes considerable resources without side effects, <!--treating the printing as being for illustrative purposes only--> and is to be minimised.
If we needed to compute the conjunction (<code>and</code>):
:<code>x = a() and b()</code>
Then it would be best to not compute the value of <math>b()</math> if the value of <math>a()</math> is computed as <math>\mathrm{false}</math>, as the value of <math>x</math> can then only ever be <math>\mathrm{false}</math>.
Similarly, if we needed to compute the disjunction (<code>or</code>):
:<code>y = a() or b()</code>
Then it would be best to not compute the value of <math>b()</math> if the value of <math>a()</math> is computed as <math>\mathrm{true}</math>, as the value of <math>y</math> can then only ever be <math>\mathrm{true}</math>.
Some languages will stop further computation of boolean equations as soon as the result is known, so-called [[wp:Short-circuit evaluation|short-circuit evaluation]] of boolean expressions
;Task Description
The task is to create two functions named <math>a</math> and <math>b</math>, that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function <math>b</math> is only called when necessary:
:<code>x = a(i) and b(j)</code>
:<code>y = a(i) or b(j)</code>
If the language does not have short-circuit evaluation, this might be achieved with nested <code>if</code> statements.

View file

@ -0,0 +1,2 @@
---
note: Programming language concepts

View file

@ -0,0 +1,38 @@
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 );
# user defined Short-circuit_evaluation procedures #
PROC or else = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ),
and then = (BOOL a, PROC BOOL b)BOOL: ( a | b | a );
test:(
PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a),
b = (BOOL b)BOOL: ( print(("b=",b,", ")); b);
CO
# Valid for Algol 68 Rev0: using "user defined" operators #
# Note: here BOOL is being automatically "procedured" to PROC BOOL #
print(("T ORELSE F = ", a(TRUE) ORELSE b(FALSE), new line));
print(("F ANDTHEN T = ", a(FALSE) ANDTHEN b(TRUE), new line));
print(("or else(T, F) = ", or else(a(TRUE), b(FALSE)), new line));
print(("and then(F, T) = ", and then(a(FALSE), b(TRUE)), new line));
END CO
# Valid for Algol68 Rev1: using "user defined" operators #
# Note: BOOL must be manually "procedured" to PROC BOOL #
print(("T ORELSE F = ", a(TRUE) ORELSE (BOOL:b(FALSE)), new line));
print(("T ORELSE T = ", a(TRUE) ORELSE (BOOL:b(TRUE)), new line));
print(("F ANDTHEN F = ", a(FALSE) ANDTHEN (BOOL:b(FALSE)), new line));
print(("F ANDTHEN T = ", a(FALSE) ANDTHEN (BOOL:b(TRUE)), new line));
print(("F ORELSE F = ", a(FALSE) ORELSE (BOOL:b(FALSE)), new line));
print(("F ORELSE T = ", a(FALSE) ORELSE (BOOL:b(TRUE)), new line));
print(("T ANDTHEN F = ", a(TRUE) ANDTHEN (BOOL:b(FALSE)), new line));
print(("T ANDTHEN T = ", a(TRUE) ANDTHEN (BOOL:b(TRUE)), new line))
)

View file

@ -0,0 +1,25 @@
test:(
PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a),
b = (BOOL b)BOOL: ( print(("b=",b,", ")); b);
# Valid for Algol 68G and 68RS using non standard operators #
print(("T OREL F = ", a(TRUE) OREL b(FALSE), new line));
print(("T OREL T = ", a(TRUE) OREL b(TRUE), new line));
print(("F ANDTH F = ", a(FALSE) ANDTH b(FALSE), new line));
print(("F ANDTH T = ", a(FALSE) ANDTH b(TRUE), new line));
print(("F OREL F = ", a(FALSE) OREL b(FALSE), new line));
print(("F OREL T = ", a(FALSE) OREL b(TRUE), new line));
print(("T ANDTH F = ", a(TRUE) ANDTH b(FALSE), new line));
print(("T ANDTH T = ", a(TRUE) ANDTH b(TRUE), new line))
CO;
# Valid for Algol 68G and 68C using non standard operators #
print(("T ORF F = ", a(TRUE) ORF b(FALSE), new line));
print(("F ANDF T = ", a(FALSE) ANDF b(TRUE), new line))
END CO
)

View file

@ -0,0 +1,27 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Short_Circuit is
function A (Value : Boolean) return Boolean is
begin
Put (" A=" & Boolean'Image (Value));
return Value;
end A;
function B (Value : Boolean) return Boolean is
begin
Put (" B=" & Boolean'Image (Value));
return Value;
end B;
begin
for I in Boolean'Range loop
for J in Boolean'Range loop
Put (" (A and then B)=" & Boolean'Image (A (I) and then B (J)));
New_Line;
end loop;
end loop;
for I in Boolean'Range loop
for J in Boolean'Range loop
Put (" (A or else B)=" & Boolean'Image (A (I) or else B (J)));
New_Line;
end loop;
end loop;
end Test_Short_Circuit;

View file

@ -0,0 +1,16 @@
i = 1
j = 1
x := a(i) and b(j)
y := a(i) or b(j)
a(p)
{
MsgBox, a() was called with the parameter "%p%".
Return, p
}
b(p)
{
MsgBox, b() was called with the parameter "%p%".
Return, p
}

View file

@ -0,0 +1,28 @@
REM TRUE is represented as -1, FALSE as 0
FOR i% = TRUE TO FALSE
FOR j% = TRUE TO FALSE
PRINT "For x=a(";FNboolstring(i%);") AND b(";FNboolstring(j%);")"
x% = FALSE
REM Short-circuit AND can be simulated by cascaded IFs:
IF FNa(i%) IF FNb(j%) THEN x%=TRUE
PRINT "x is ";FNboolstring(x%)
PRINT
PRINT "For y=a(";FNboolstring(i%);") OR b(";FNboolstring(j%);")"
y% = FALSE
REM Short-circuit OR can be simulated by De Morgan's laws:
IF NOTFNa(i%) IF NOTFNb(j%) ELSE y%=TRUE : REM Note ELSE without THEN
PRINT "y is ";FNboolstring(y%)
PRINT
NEXT:NEXT
END
DEFFNa(bool%)
PRINT "Function A used; ";
=bool%
DEFFNb(bool%)
PRINT "Function B used; ";
=bool%
DEFFNboolstring(bool%)
IF bool%=0 THEN ="FALSE" ELSE="TRUE"

View file

@ -0,0 +1,27 @@
#include <iostream>
bool a(bool in)
{
std::cout << "a" << std::endl;
return in;
}
bool b(bool in)
{
std::cout << "b" << std::endl;
return in;
}
void test(bool i, bool j) {
std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl;
std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl;
}
int main()
{
test(false, false);
test(false, true);
test(true, false);
test(true, true);
return 0;
}

View file

@ -0,0 +1,32 @@
#include <stdio.h>
#include <stdbool.h>
bool a(bool in)
{
printf("I am a\n");
return in;
}
bool b(bool in)
{
printf("I am b\n");
return in;
}
#define TEST(X,Y,O) \
do { \
x = a(X) O b(Y); \
printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \
} while(false);
int main()
{
bool x;
TEST(false, true, &&); // b is not evaluated
TEST(true, false, ||); // b is not evaluated
TEST(true, false, &&); // b is evaluated
TEST(false, false, ||); // b is evaluated
return 0;
}

View file

@ -0,0 +1,7 @@
(letfn [(a [bool] (print "(a)") bool)
(b [bool] (print "(b)") bool)]
(doseq [i [true false] j [true false]]
(print i "OR" j "= ")
(println (or (a i) (b j)))
(print i "AND" j " = ")
(println (and (a i) (b j)))))

View file

@ -0,0 +1,13 @@
(defun a (F)
(print 'a)
F )
(defun b (F)
(print 'b)
F )
(dolist (x '((nil nil) (nil T) (T T) (T nil)))
(format t "~%(and ~S)" x)
(and (a (car x)) (b (car(cdr x))))
(format t "~%(or ~S)" x)
(or (a (car x)) (b (car(cdr x)))))

View file

@ -0,0 +1,21 @@
import std.stdio, std.algorithm;
T a(T)(T answer) {
writefln(" # Called function a(%s) -> %s", answer, answer);
return answer;
}
T b(T)(T answer) {
writefln(" # Called function b(%s) -> %s", answer, answer);
return answer;
}
void main() {
foreach (immutable x, immutable y;
[false, true].cartesianProduct([false, true])) {
writeln("\nCalculating: r1 = a(x) && b(y)");
immutable r1 = a(x) && b(y);
writeln("Calculating: r2 = a(x) || b(y)");
immutable r2 = a(x) || b(y);
}
}

View file

@ -0,0 +1,32 @@
program ShortCircuitEvaluation;
{$APPTYPE CONSOLE}
uses SysUtils;
function A(aValue: Boolean): Boolean;
begin
Writeln('a');
Result := aValue;
end;
function B(aValue: Boolean): Boolean;
begin
Writeln('b');
Result := aValue;
end;
var
i, j: Boolean;
begin
for i in [False, True] do
begin
for j in [False, True] do
begin
Writeln(Format('%s and %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) and B(j), True)]));
Writeln;
Writeln(Format('%s or %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) or B(j), True)]));
Writeln;
end;
end;
end.

View file

@ -0,0 +1,5 @@
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)

View file

@ -0,0 +1 @@
def x := a(i) && (def funky := b(j))

View file

@ -0,0 +1,28 @@
class Main
{
static Bool a (Bool value)
{
echo ("in a")
return value
}
static Bool b (Bool value)
{
echo ("in b")
return value
}
public static Void main ()
{
[false,true].each |i|
{
[false,true].each |j|
{
Bool result := a(i) && b(j)
echo ("a($i) && b($j): " + result)
result = a(i) || b(j)
echo ("a($i) || b($j): " + result)
}
}
}
}

View file

@ -0,0 +1,20 @@
\ short-circuit conditional syntax, from Wil Baden
: COND 0 ; immediate
: THENS BEGIN dup WHILE postpone THEN REPEAT DROP ; immediate
: ORIF s" ?DUP 0= IF" evaluate ; immediate
: ANDIF s" DUP IF DROP" evaluate ; immediate
: .bool IF ." true " ELSE ." false" THEN ;
: A ." A=" dup .bool ;
: B ." B=" dup .bool ;
: test
1 -1 DO 1 -1 DO
CR I A drop space J B drop space
." : ANDIF " COND I A ANDIF drop J B IF ." (BOTH)" THENS
." , ORIF " COND I A ORIF drop J B 0= IF ." (NEITHER)" THENS
LOOP LOOP ;
\ a more typical example
: alnum? ( char -- ? )
COND dup lower? ORIF dup upper? ORIF dup digit? THENS nip ;

View file

@ -0,0 +1,51 @@
program Short_Circuit_Eval
implicit none
logical :: x, y
logical, dimension(2) :: l = (/ .false., .true. /)
integer :: i, j
do i = 1, 2
do j = 1, 2
write(*, "(a,l1,a,l1,a)") "Calculating x = a(", l(i), ") and b(", l(j), ")"
! a AND b
x = a(l(i))
if(x) then
x = b(l(j))
write(*, "(a,l1)") "x = ", x
else
write(*, "(a,l1)") "x = ", x
end if
write(*,*)
write(*, "(a,l1,a,l1,a)") "Calculating y = a(", l(i), ") or b(", l(j), ")"
! a OR b
y = a(l(i))
if(y) then
write(*, "(a,l1)") "y = ", y
else
y = b(l(j))
write(*, "(a,l1)") "y = ", y
end if
write(*,*)
end do
end do
contains
function a(value)
logical :: a
logical, intent(in) :: value
a = value
write(*, "(a,l1,a)") "Called function a(", value, ")"
end function
function b(value)
logical :: b
logical, intent(in) :: value
b = value
write(*, "(a,l1,a)") "Called function b(", value, ")"
end function
end program

View file

@ -0,0 +1,32 @@
package main
import "fmt"
func a(v bool) bool {
fmt.Print("a")
return v
}
func b(v bool) bool {
fmt.Print("b")
return v
}
func test(i, j bool) {
fmt.Printf("Testing a(%t) && b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) && b(j))
fmt.Printf("Testing a(%t) || b(%t)\n", i, j)
fmt.Print("Trace: ")
fmt.Println("\nResult:", a(i) || b(j))
fmt.Println("")
}
func main() {
test(false, false)
test(false, true)
test(true, false)
test(true, true)
}

View file

@ -0,0 +1,15 @@
def f = { println ' AHA!'; it instanceof String }
def g = { printf ('%5d ', it); it > 50 }
println 'bitwise'
assert g(100) & f('sss')
assert g(2) | f('sss')
assert ! (g(1) & f('sss'))
assert g(200) | f('sss')
println '''
logical'''
assert g(100) && f('sss')
assert g(2) || f('sss')
assert ! (g(1) && f('sss'))
assert g(200) || f('sss')

View file

@ -0,0 +1,18 @@
module ShortCircuit where
import Prelude hiding ((&&), (||))
import Debug.Trace
False && _ = False
True && False = False
_ && _ = True
True || _ = True
False || True = True
_ || _ = False
a p = trace ("<a " ++ show p ++ ">") p
b p = trace ("<b " ++ show p ++ ">") p
main = mapM_ print ( [ a p || b q | p <- [False, True], q <- [False, True] ]
++ [ a p && b q | p <- [False, True], q <- [False, True] ])

View file

@ -0,0 +1,7 @@
_ && False = False
False && True = False
_ && _ = True
_ || True = True
True || False = True
_ || _ = False

View file

@ -0,0 +1,11 @@
p && q = case p of
False -> False
_ -> case q of
False -> False
_ -> True
p || q = case p of
True -> True
_ -> case q of
True -> True
_ -> False

View file

@ -0,0 +1,19 @@
procedure main()
&trace := -1 # ensures functions print their names
every (i := false | true ) & ( j := false | true) do {
write("i,j := ",image(i),", ",image(j))
write("i & j:")
x := i() & j() # invoke true/false
write("i | j:")
y := i() | j() # invoke true/false
}
end
procedure true() #: succeeds always (returning null)
return
end
procedure false() #: fails always
fail # for clarity but not needed as running into end has the same effect
end

View file

@ -0,0 +1,5 @@
labeled=:1 :'[ smoutput@,&":~&m'
A=: 'A ' labeled
B=: 'B ' labeled
and=: ^:
or=: 2 :'u^:(-.@v)'

View file

@ -0,0 +1,14 @@
(A and B) 1
B 1
A 1
1
(A and B) 0
B 0
0
(A or B) 1
B 1
1
(A or B) 0
B 0
A 0
0

View file

@ -0,0 +1,25 @@
public class ShortCirc {
public static void main(String[] args){
System.out.println("F and F = " + (a(false) && b(false)) + "\n");
System.out.println("F or F = " + (a(false) || b(false)) + "\n");
System.out.println("F and T = " + (a(false) && b(true)) + "\n");
System.out.println("F or T = " + (a(false) || b(true)) + "\n");
System.out.println("T and F = " + (a(true) && b(false)) + "\n");
System.out.println("T or F = " + (a(true) || b(false)) + "\n");
System.out.println("T and T = " + (a(true) && b(true)) + "\n");
System.out.println("T or T = " + (a(true) || b(true)) + "\n");
}
public static boolean a(boolean a){
System.out.println("a");
return a;
}
public static boolean b(boolean b){
System.out.println("b");
return b;
}
}

View file

@ -0,0 +1,6 @@
a(x) = (println(" # Called function a($x) -> $x"); return x)
b(x) = (println(" # Called function a($x) -> $x"); return x)
for i in [true,false], j in [true, false]
println("\nCalculating: x = a(i) && b(j)"); x = a(i) && b(j)
println("\nCalculating: y = a(i) || b(j)"); y = a(i) && b(j)
end

View file

@ -0,0 +1,35 @@
print "AND"
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") AND b( "; j; ")"
res =a( i) 'call always
if res <>0 then 'short circuit if 0
res = b( j)
end if
print "=>",res
next
next
print "---------------------------------"
print "OR"
for i = 0 to 1
for j = 0 to 1
print "a("; i; ") AND b("; j; ")"
res =a( i) 'call always
if res = 0 then 'short circuit if <>0
res = b( j)
end if
print "=>", res
next
next
'----------------------------------------
function a( t)
print ,"calls func a"
a = t
end function
function b( t)
print ,"calls func b"
b = t
end function

View file

@ -0,0 +1,2 @@
and [notequal? :x 0] [1/:x > 3]
(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y < 3])

View file

@ -0,0 +1,17 @@
function a(i)
print "Function a(i) called."
return i
end
function b(i)
print "Function b(i) called."
return i
end
i = true
x = a(i) and b(i); print ""
y = a(i) or b(i); print ""
i = false
x = a(i) and b(i); print ""
y = a(i) or b(i)

View file

@ -0,0 +1,11 @@
function x=a(x)
printf('a: %i\n',x);
end;
function x=b(x)
printf('b: %i\n',x);
end;
a(1) && b(1)
a(0) && b(1)
a(1) || b(1)
a(0) || b(1)

View file

@ -0,0 +1,10 @@
> a(1) && b(1);
a: 1
b: 1
> a(0) && b(1);
a: 0
> a(1) || b(1);
a: 1
> a(0) || b(1);
a: 0
b: 1

View file

@ -0,0 +1,22 @@
SSEVAL1(IN)
WRITE !,?10,$STACK($STACK,"PLACE")
QUIT IN
SSEVAL2(IN)
WRITE !,?10,$STACK($STACK,"PLACE")
QUIT IN
SSEVAL3
NEW Z
WRITE "1 AND 1"
SET Z=$$SSEVAL1(1) SET:Z Z=Z&$$SSEVAL2(1)
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
WRITE !!,"0 AND 1"
SET Z=$$SSEVAL1(0) SET:Z Z=Z&$$SSEVAL2(1)
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
WRITE !!,"1 OR 1"
SET Z=$$SSEVAL1(1) SET:'Z Z=Z!$$SSEVAL2(1)
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
WRITE !!,"0 OR 1"
SET Z=$$SSEVAL1(0) SET:'Z Z=Z!$$SSEVAL2(1)
WRITE !,$SELECT(Z:"TRUE",1:"FALSE")
KILL Z
QUIT

View file

@ -0,0 +1,5 @@
a[in_] := (Print["a"]; in)
b[in_] := (Print["b"]; in)
a[False] && b[True]
a[True] || b[False]

View file

@ -0,0 +1 @@
a[True] && b[False]

View file

@ -0,0 +1,31 @@
using System.Console;
class ShortCircuit
{
public static a(x : bool) : bool
{
WriteLine("a");
x
}
public static b(x : bool) : bool
{
WriteLine("b");
x
}
public static Main() : void
{
def t = true;
def f = false;
WriteLine("True && True : {0}", a(t) && b(t));
WriteLine("True && False: {0}", a(t) && b(f));
WriteLine("False && True : {0}", a(f) && b(t));
WriteLine("False && False: {0}", a(f) && b(f));
WriteLine("True || True : {0}", a(t) || b(t));
WriteLine("True || False: {0}", a(t) || b(f));
WriteLine("False || True : {0}", a(f) || b(t));
WriteLine("False || False: {0}", a(f) || b(f));
}
}

View file

@ -0,0 +1,20 @@
a
b
True && True : True
a
b
True && False: False
a
False && True : False
a
False && False: False
a
True || True : True
a
True || False: True
a
b
False || True : True
a
b
False || False: False

View file

@ -0,0 +1,24 @@
let a r = print_endline " > function a called"; r
let b r = print_endline " > function b called"; r
let test_and b1 b2 =
Printf.printf "# testing (%b && %b)\n" b1 b2;
ignore (a b1 && b b2)
let test_or b1 b2 =
Printf.printf "# testing (%b || %b)\n" b1 b2;
ignore (a b1 || b b2)
let test_this test =
test true true;
test true false;
test false true;
test false false;
;;
let () =
print_endline "==== Testing and ====";
test_this test_and;
print_endline "==== Testing or ====";
test_this test_or;
;;

View file

@ -0,0 +1,27 @@
bundle Default {
class ShortCircuit {
function : a(a : Bool) ~ Bool {
"a"->PrintLine();
return a;
}
function : b(b : Bool) ~ Bool {
"b"->PrintLine();
return b;
}
function : Main(args : String[]) ~ Nil {
IO.Console->Instance()->Print("F and F = ")->PrintLine(a(false) & b(false));
IO.Console->Instance()->Print("F or F = ")->PrintLine(a(false) | b(false));
IO.Console->Instance()->Print("F and T = ")->PrintLine(a(false) & b(true));
IO.Console->Instance()->Print("F or T = ")->PrintLine(a(false) | b(true));
IO.Console->Instance()->Print("T and F = ")->PrintLine(a(true) & b(false));
IO.Console->Instance()->Print("T or F = ")->PrintLine(a(true) | b(false));
IO.Console->Instance()->Print("T and T = ")->PrintLine(a(true) & b(true));
IO.Console->Instance()->Print("T or T = ")->PrintLine(a(true) | b(true));
}
}
}

View file

@ -0,0 +1,25 @@
declare
fun {A Answer}
AnswerS = {Value.toVirtualString Answer 1 1}
in
{System.showInfo " % Called function {A "#AnswerS#"} -> "#AnswerS}
Answer
end
fun {B Answer}
AnswerS = {Value.toVirtualString Answer 1 1}
in
{System.showInfo " % Called function {B "#AnswerS#"} -> "#AnswerS}
Answer
end
in
for I in [false true] do
for J in [false true] do
X Y
in
{System.showInfo "\nCalculating: X = {A I} andthen {B J}"}
X = {A I} andthen {B J}
{System.showInfo "Calculating: Y = {A I} orelse {B J}"}
Y = {A I} orelse {B J}
end
end

View file

@ -0,0 +1,23 @@
Calculating: X = {A I} andthen {B J}
% Called function {A false} -> false
Calculating: Y = {A I} orelse {B J}
% Called function {A false} -> false
% Called function {B false} -> false
Calculating: X = {A I} andthen {B J}
% Called function {A false} -> false
Calculating: Y = {A I} orelse {B J}
% Called function {A false} -> false
% Called function {B true} -> true
Calculating: X = {A I} andthen {B J}
% Called function {A true} -> true
% Called function {B false} -> false
Calculating: Y = {A I} orelse {B J}
% Called function {A true} -> true
Calculating: X = {A I} andthen {B J}
% Called function {A true} -> true
% Called function {B true} -> true
Calculating: Y = {A I} orelse {B J}
% Called function {A true} -> true

View file

@ -0,0 +1,14 @@
a(n)={
print(a"("n")");
a
};
b(n)={
print("b("n")");
n
};
or(A,B)={
a(A) || b(B)
};
and(A,B)={
a(A) && b(B)
};

View file

@ -0,0 +1,35 @@
short_circuit_evaluation:
procedure options (main);
declare (true initial ('1'b), false initial ('0'b) ) bit (1);
declare (i, j, x, y) bit (1);
a: procedure (bv) returns (bit(1));
declare bv bit(1);
put ('Procedure ' || procedurename() || ' called.');
return (bv);
end a;
b: procedure (bv) returns (bit(1));
declare bv bit(1);
put ('Procedure ' || procedurename() || ' called.');
return (bv);
end b;
do i = true, false;
do j = true, false;
put skip(2) list ('Evaluating x with <a> with ' || i || ' and <b> with ' || j);
put skip;
if a(i) then
x = b(j);
else
x = false;
put skip data (x);
put skip(2) list ('Evaluating y with <a> with ' || i || ' and <b> with ' || j);
put skip;
if a(i) then
y = true;
else
y = b(j);
put skip data (y);
end;
end;
end short_circuit_evaluation;

View file

@ -0,0 +1,41 @@
program shortcircuit(output);
function a(value: boolean): boolean;
begin
writeln('a(', value, ')');
a := value
end;
function b(value:boolean): boolean;
begin
writeln('b(', value, ')');
b := value
end;
procedure scandor(value1, value2: boolean);
var
result: boolean;
begin
{and}
if a(value1)
then
result := b(value2)
else
result := false;
writeln(value1, ' and ', value2, ' = ', result);
{or}
if a(value1)
then
result := true
else
result := b(value2)
writeln(value1, ' or ', value2, ' = ', result);
end;
begin
scandor(false, false);
scandor(false, true);
scandor(true, false);
scandor(true, true);
end.

View file

@ -0,0 +1,32 @@
program shortcircuit;
function a(value: boolean): boolean;
begin
writeln('a(', value, ')');
a := value;
end;
function b(value:boolean): boolean;
begin
writeln('b(', value, ')');
b := value;
end;
{$B-} {enable short circuit evaluation}
procedure scandor(value1, value2: boolean);
var
result: boolean;
begin
result := a(value1) and b(value);
writeln(value1, ' and ', value2, ' = ', result);
result := a(value1) or b(value2);
writeln(value1, ' or ', value2, ' = ', result);
end;
begin
scandor(false, false);
scandor(false, true);
scandor(true, false);
scandor(true, true);
end.

View file

@ -0,0 +1,31 @@
program shortcircuit(output);
function a(value: boolean): boolean;
begin
writeln('a(', value, ')');
a := value
end;
function b(value:boolean): boolean;
begin
writeln('b(', value, ')');
b := value
end;
procedure scandor(value1, value2: boolean);
var
result: integer;
begin
result := a(value1) and_then b(value)
writeln(value1, ' and ', value2, ' = ', result);
result := a(value1) or_else b(value2);
writeln(value1, ' or ', value2, ' = ', result)
end;
begin
scandor(false, false);
scandor(false, true);
scandor(true, false);
scandor(true, true);
end.

View file

@ -0,0 +1,11 @@
sub a ($p) { print 'a'; $p }
sub b ($p) { print 'b'; $p }
for '&&', '||' -> $op {
for True, False X True, False -> $p, $q {
my $s = "a($p) $op b($q)";
print "$s: ";
eval $s;
print "\n";
}
}

View file

@ -0,0 +1,14 @@
sub a { print 'A'; return $_[0] }
sub b { print 'B'; return $_[0] }
# Test-driver
sub test {
for my $op ('&&','||') {
for (qw(1,1 1,0 0,1 0,0)) {
my ($x,$y) = /(.),(.)/;
print my $str = "a($x) $op b($y)", ': ';
eval $str; print "\n"; } }
}
# Test and display
test();

View file

@ -0,0 +1,14 @@
(de a (F)
(msg 'a)
F )
(de b (F)
(msg 'b)
F )
(mapc
'((I J)
(for Op '(and or)
(println I Op J '-> (Op (a I) (b J))) ) )
'(NIL NIL T T)
'(NIL T NIL T) )

View file

@ -0,0 +1,20 @@
int(0..1) a(int(0..1) i)
{
write(" a\n");
return i;
}
int(0..1) b(int(0..1) i)
{
write(" b\n");
return i;
}
foreach(({ ({ false, false }), ({ false, true }), ({ true, true }), ({ true, false }) });; array(int) args)
{
write(" %d && %d\n", @args);
a(args[0]) && b(args[1]);
write(" %d || %d\n", @args);
a(args[0]) || b(args[1]);
}

View file

@ -0,0 +1,26 @@
short_circuit :-
( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl,
( a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , nl,
( a_and_b(true, true)-> writeln('==> true'); writeln('==> false')) , nl,
( a_and_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl,
( a_and_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl,
( a_and_b(false, false)-> writeln('==> true'); writeln('==> false')) .
a_and_b(X, Y) :-
format('a(~w) and b(~w)~n', [X, Y]),
( a(X), b(Y)).
a_or_b(X, Y) :-
format('a(~w) or b(~w)~n', [X, Y]),
( a(X); b(Y)).
a(X) :-
format('a(~w)~n', [X]),
X.
b(X) :-
format('b(~w)~n', [X]),
X.

View file

@ -0,0 +1,38 @@
?- short_circuit.
a(true) or b(true)
a(true)
==> true
a(true) or b(false)
a(true)
==> true
a(false) or b(true)
a(false)
b(true)
==> true
a(false) or b(false)
a(false)
b(false)
==> false
a(true) and b(true)
a(true)
b(true)
==> true
a(true) and b(false)
a(true)
b(false)
==> false
a(false) and b(true)
a(false)
==> false
a(false) and b(false)
a(false)
==> false
true.

View file

@ -0,0 +1,20 @@
Procedure a(arg)
PrintN(" # Called function a("+Str(arg)+")")
ProcedureReturn arg
EndProcedure
Procedure b(arg)
PrintN(" # Called function b("+Str(arg)+")")
ProcedureReturn arg
EndProcedure
OpenConsole()
For a=#False To #True
For b=#False To #True
PrintN(#CRLF$+"Calculating: x = a("+Str(a)+") And b("+Str(b)+")")
x= a(a) And b(b)
PrintN("Calculating: x = a("+Str(a)+") Or b("+Str(b)+")")
y= a(a) Or b(b)
Next
Next
Input()

View file

@ -0,0 +1,40 @@
>>> def a(answer):
print(" # Called function a(%r) -> %r" % (answer, answer))
return answer
>>> def b(answer):
print(" # Called function b(%r) -> %r" % (answer, answer))
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
# Called function a(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(False) -> False
# Called function b(False) -> False
Calculating: x = a(i) and b(j)
# Called function a(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(False) -> False
# Called function b(True) -> True
Calculating: x = a(i) and b(j)
# Called function a(True) -> True
# Called function b(False) -> False
Calculating: y = a(i) or b(j)
# Called function a(True) -> True
Calculating: x = a(i) and b(j)
# Called function a(True) -> True
# Called function b(True) -> True
Calculating: y = a(i) or b(j)
# Called function a(True) -> True

View file

@ -0,0 +1,32 @@
>>> 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")
x = b(j) if a(i) else False
print ("Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True")
y = b(j) if not a(i) else True
Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
# Called function a(False) -> False
Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True
# Called function a(False) -> False
# Called function b(False) -> False
Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
# Called function a(False) -> False
Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True
# Called function a(False) -> False
# Called function b(True) -> True
Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
# Called function a(True) -> True
# Called function b(False) -> False
Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True
# Called function a(True) -> True
Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False
# Called function a(True) -> True
# 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

View file

@ -0,0 +1,9 @@
a <- function(x) {cat("a called\n"); x}
b <- function(x) {cat("b called\n"); x}
tests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0))
invisible(apply(tests, 1, function(row) {
call <- substitute(op(a(x),b(y)), row)
cat(deparse(call), "->", eval(call), "\n\n")
}))

View file

@ -0,0 +1,27 @@
a called
a(1) || b(1) -> TRUE
a called
b called
a(1) && b(1) -> TRUE
a called
b called
a(0) || b(1) -> TRUE
a called
a(0) && b(1) -> FALSE
a called
a(1) || b(0) -> TRUE
a called
b called
a(1) && b(0) -> FALSE
a called
b called
a(0) || b(0) -> FALSE
a called
a(0) && b(0) -> FALSE

View file

@ -0,0 +1,5 @@
switchop <- function(s, x, y) {
if(s < 0) x || y
else if (s > 0) x && y
else xor(x, y)
}

View file

@ -0,0 +1,14 @@
> switchop(-1, a(1), b(1))
a called
[1] TRUE
> switchop(1, a(1), b(1))
a called
b called
[1] TRUE
> switchop(1, a(0), b(1))
a called
[1] FALSE
> switchop(0, a(0), b(1))
a called
b called
[1] TRUE

View file

@ -0,0 +1,12 @@
/*REXX programs demonstrates short-circuit evaulation testing. */
do i=-2 to 2
x=a(i) & b(i)
y=a(i)
if \y then y=b(i)
say copies('',30) 'x='||x 'y='y 'i='i
end /*j*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────subroutines─────────────────────────*/
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*/

View file

@ -0,0 +1,18 @@
#lang racket
(define (a x)
(display (~a "a:" x " "))
x)
(define (b x)
(display (~a "b:" x " "))
x)
(for* ([x '(#t #f)]
[y '(#t #f)])
(displayln `(and (a ,x) (b ,y)))
(and (a x) (b y))
(newline)
(displayln `(or (a ,x) (b ,y)))
(or (a x) (b y))
(newline))

View file

@ -0,0 +1,18 @@
def a( bool )
puts "a( #{bool} ) called"
bool
end
def b( bool )
puts "b( #{bool} ) called"
bool
end
[true, false].each do |a_val|
[true, false].each do |b_val|
puts "a( #{a_val} ) and b( #{b_val} ) is #{a( a_val ) and b( b_val )}."
puts
puts "a( #{a_val} ) or b( #{b_val} ) is #{a( a_val) or b( b_val )}."
puts
end
end

View file

@ -0,0 +1,26 @@
define('a(val)') :(a_end)
a out = 'A '
eq(val,1) :s(return)f(freturn)
a_end
define('b(val)') :(b_end)
b out = 'B '
eq(val,1) :s(return)f(freturn)
b_end
* # Test and display
&fullscan = 1
output(.out,1,'-[-r1]') ;* Macro Spitbol
* output(.out,1,'B','-') ;* CSnobol
define('nl()'):(nlx);nl output = :(return);nlx
out = 'T and T: '; null ? *a(1) *b(1); nl()
out = 'T and F: '; null ? *a(1) *b(0); nl()
out = 'F and T: '; null ? *a(0) *b(1); nl()
out = 'F and F: '; null ? *a(0) *b(0); nl()
output =
out = 'T or T: '; null ? *a(1) | *b(1); nl()
out = 'T or F: '; null ? *a(1) | *b(0); nl()
out = 'F or T: '; null ? *a(0) | *b(1); nl()
out = 'F or F: '; null ? *a(0) | *b(0); nl()
end

View file

@ -0,0 +1,26 @@
class MAIN is
a(v:BOOL):BOOL is
#OUT + "executing a\n";
return v;
end;
b(v:BOOL):BOOL is
#OUT + "executing b\n";
return v;
end;
main is
x:BOOL;
x := a(false) and b(true);
#OUT + "F and T = " + x + "\n\n";
x := a(true) or b(true);
#OUT + "T or T = " + x + "\n\n";
x := a(true) and b(false);
#OUT + "T and T = " + x + "\n\n";
x := a(false) or b(true);
#OUT + "F or T = " + x + "\n\n";
end;
end;

View file

@ -0,0 +1,17 @@
object ShortCircuit {
def a(b:Boolean)={print("Called A=%5b".format(b));b}
def b(b:Boolean)={print(" -> B=%5b".format(b));b}
def main(args: Array[String]): Unit = {
val boolVals=List(false,true)
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b AND B=%5b -> ".format(aa, bb))
a(aa) && b(bb)
}
for(aa<-boolVals; bb<-boolVals){
print("\nTesting A=%5b OR B=%5b -> ".format(aa, bb))
a(aa) || b(bb)
}
println
}
}

View file

@ -0,0 +1,34 @@
>(define (a x)
(display "a\n")
x)
>(define (b x)
(display "b\n")
x)
>(for-each (lambda (i)
(for-each (lambda (j)
(display i) (display " and ") (display j) (newline)
(and (a i) (b j))
(display i) (display " or ") (display j) (newline)
(or (a i) (b j))
) '(#t #f))
) '(#t #f))
#t and #t
a
b
#t or #t
a
#t and #f
a
b
#t or #f
a
#f and #t
a
#f or #t
a
b
#f and #f
a
#f or #f
a
b

View file

@ -0,0 +1,31 @@
$ include "seed7_05.s7i";
const func boolean: a (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("a");
result := aBool;
end func;
const func boolean: b (in boolean: aBool) is func
result
var boolean: result is FALSE;
begin
writeln("b");
result := aBool;
end func;
const proc: test (in boolean: param1, in boolean: param2) is func
begin
writeln(param1 <& " and " <& param2 <& " = " <& a(param1) and b(param2));
writeln(param1 <& " or " <& param2 <& " = " <& a(param1) or b(param2));
end func;
const proc: main is func
begin
test(FALSE, FALSE);
test(FALSE, TRUE);
test(TRUE, FALSE);
test(TRUE, TRUE);
end func;

View file

@ -0,0 +1,21 @@
Smalltalk at: #a put: nil.
Smalltalk at: #b put: nil.
a := [:x| 'executing a' displayNl. x].
b := [:x| 'executing b' displayNl. x].
('false and false = %1' %
{ (a value: false) and: [ b value: false ] })
displayNl.
('true or false = %1' %
{ (a value: true) or: [ b value: false ] })
displayNl.
('false or true = %1' %
{ (a value: false) or: [ b value: true ] })
displayNl.
('true and false = %1' %
{ (a value: true) and: [ b value: false ] })
displayNl.

View file

@ -0,0 +1,22 @@
fun a r = ( print " > function a called\n"; r )
fun b r = ( print " > function b called\n"; r )
fun test_and b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " andalso " ^ Bool.toString b2 ^ ")\n");
ignore (a b1 andalso b b2) )
fun test_or b1 b2 = (
print ("# testing (" ^ Bool.toString b1 ^ " orelse " ^ Bool.toString b2 ^ ")\n");
ignore (a b1 orelse b b2) )
fun test_this test = (
test true true;
test true false;
test false true;
test false false )
;
print "==== Testing and ====\n";
test_this test_and;
print "==== Testing or ====\n";
test_this test_or;

View file

@ -0,0 +1,35 @@
@(define a (x out))
@ (output)
a (@x) called
@ (end)
@ (bind out x)
@(end)
@(define b (x out))
@ (output)
b (@x) called
@ (end)
@ (bind out x)
@(end)
@(define short_circuit_demo (i j))
@ (output)
a(@i) and b(@j):
@ (end)
@ (maybe)
@ (a i "1")
@ (b j "1")
@ (end)
@ (output)
a(@i) or b(@j):
@ (end)
@ (cases)
@ (a i "1")
@ (or)
@ (b j "1")
@ (or)
@ (accept)
@ (end)
@(end)
@(short_circuit_demo "0" "0")
@(short_circuit_demo "0" "1")
@(short_circuit_demo "1" "0")
@(short_circuit_demo "1" "1")

View file

@ -0,0 +1,19 @@
package require Tcl 8.5
proc tcl::mathfunc::a boolean {
puts "a($boolean) called"
return $boolean
}
proc tcl::mathfunc::b boolean {
puts "b($boolean) called"
return $boolean
}
foreach i {false true} {
foreach j {false true} {
set x [expr {a($i) && b($j)}]
puts "x = a($i) && b($j) = $x"
set y [expr {a($i) || b($j)}]
puts "y = a($i) || b($j) = $y"
puts ""; # Blank line for clarity
}
}

View file

@ -0,0 +1,19 @@
a() {
echo "Called a $1"
"$1"
}
b() {
echo "Called b $1"
"$1"
}
for i in false true; do
for j in false true; do
a $i && b $j && x=true || x=false
echo " $i && $j is $x"
a $i || b $j && y=true || y=false
echo " $i || $j is $y"
done
done

View file

@ -0,0 +1,12 @@
alias a eval \''echo "Called a \!:1"; "\!:1"'\'
alias b eval \''echo "Called b \!:1"; "\!:1"'\'
foreach i (false true)
foreach j (false true)
a $i && b $j && set x=true || set x=false
echo " $i && $j is $x"
a $i || b $j && set x=true || set x=false
echo " $i || $j is $x"
end
end

View file

@ -0,0 +1,8 @@
# Succeeds, only prints "ok".
if ( 1 || { echo This command never runs. } ) echo ok
# Fails, aborts shell with "bad: Undefined variable".
if ( 1 || $bad ) echo ok
# Prints "error", then "ok".
if ( 1 || `echo error >/dev/stderr` ) echo ok