Logical operations
From Rosetta Code
You are encouraged to solve this task according to the task description, using any language you may know.
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments. If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose.
If the language supports additional logical operations on booleans such as XOR, list them as well.
[edit] Ada
I have also included logical xor because it is defined for Ada boolean types. All the operators below work equally well on arrays of boolean types. In fact, a packed array of boolean is an array of bits, providing a direct link between logical and bitwise operations.
procedure Print_Logic(A : Boolean; B : Boolean) is
begin
Put_Line("A and B is " & Boolean'Image(A and B));
Put_Line("A or B is " & Boolean'Image(A or B));
Put_Line("A xor B is " & Boolean'Image(A xor B));
Put_Line("not A is " & Boolean'Image(not A));
end Print_Logic;
[edit] Aikido
function logic(a,b) {
println("a AND b: " + (a && b))
println("a OR b: " + (a || b))
println("NOT a: " + (!a))
}
[edit] ALGOL 68
PROC print_logic = (BOOL a, b)VOID:
(
# for a 6-7 bit/byte compiler #
printf(($"a and b is "gl$, a AND b);
printf(($"a or b is "gl$, a OR b);
printf(($"not a is "gl$, NOT a);
printf(($"a equivalent to b is "gl$, a EQ b);
printf(($"a not equivalent to b is "gl$, a NE b);
# Alternatively ASCII #
printf(($"a and b is "gl$, a & b);
printf(($"a and b is "gl$, a /\ b); <!-- http://web.archive.org/web/20021207211127/http://www.bobbemer.com/BRACES.HTM -->
printf(($"a or b is "gl$, a \/ b);
printf(($"a equivalent to b "gl$, a = b);
printf(($"a not equivalent to b "gl$, a /= b);
¢ for a European 8 bit/byte charcter set eg. ALCOR or GOST ¢
printf(($"a and b is "gl$, a ∧ b);
printf(($"a or b is "gl$, a ∨ b);
printf(($"not a is "gl$, ¬ a)
printf(($"a not equivalent to b is "gl$, a ≠ b)
)
[edit] AutoHotkey
a = 1
b = 0
msgbox % "a and b is " . (a && b)
msgbox % "a or b is " . (a || b)
msgbox % "not a is " . (!a)
[edit] AWK
$ awk '{print "and:"($1&&$2),"or:"($1||$2),"not:"!$1}'
0 0
and:0 or:0 not:1
0 1
and:0 or:1 not:1
1 0
and:0 or:1 not:0
1 1
and:1 or:1 not:0
[edit] BASIC
Works with: QuickBasic version 4.5
SUB logic (a%, b%) 'no booleans in BASIC...these are integers. 1 for true 0 for false. PRINT a AND b PRINT a OR b PRINT NOT a END SUB
[edit] C
void print_logic(int a, int b)
{
printf("a and b is %d\n", a && b);
printf("a or b is %d\n", a || b);
printf("not a is %d\n", !a);
}
[edit] C++
void print_logic(bool a, bool b)
{
std::cout << std::boolalpha; // so that bools are written as "true" and "false"
std::cout << "a and b is " << (a && b) << "\n";
std::cout << "a or b is " << (a || b) << "\n";
std::cout << "not a is " << (!a) << "\n";
}
[edit] C#
using System;
namespace LogicalOperations
{
class Program
{
static void Main(string[] args)
{
bool a = true, b = false;
Console.WriteLine("a and b is {0}", a && b);
Console.WriteLine("a or b is {0}", a || b);
Console.WriteLine("Not a is {0}", !a);
Console.WriteLine("a exclusive-or b is {0}", a ^ b);
}
}
}
[edit] Clojure
(defn logical [a b]
(prn (str "a and b is " (and a b)))
(prn (str "a or b is " (or a b)))
(prn (str "not a is " (not a))))
(logical true false)
[edit] ColdFusion
<cffunction name = "logic" hint = "Performs basic logical operations">
<cfargument name = "a" required = "yes" type = "boolean" />
<cfargument name = "a" required = "yes" type = "boolean" />
<cfoutput>
'A' AND 'B' is #a AND b#< br />
'A' OR 'B' is #a OR b#< br />
NOT 'A' is #!a#
</cfoutput>
</cffunction>
[edit] Common Lisp
(defun logic (a b)
(print "a and b is") (write (and a b))
(print "a or b is" ) (write (or a b))
(print "not a is" ) (write (not a)))
[edit] D
module andOr ;
import std.stdio ;
void logic(T,U)(T lhs, U rhs){
writefln("'%s' is of type '%s', '%s' is of type '%s';",
lhs,typeid(typeof(lhs)), rhs,typeid(typeof(rhs))) ;
writefln("\t'%s' AND '%s' is %s, ", lhs, rhs, lhs && rhs) ;
writefln("\t'%s' OR '%s' is %s, ", lhs, rhs, lhs || rhs) ;
writefln("\tNOT '%s' is %s.\n", lhs, !lhs) ;
}
class C {int value ; }
void main() {
bool theTruth = true ;
bool theLie = false ;
real zeroReal = 0.0L ;
real NaN ; // D init. float type to NaN ;
int zeroInt = 0 ;
real[] nullArr = null ;
string emptyStr = "" ;
string nullStr = null ;
C someC = new C ;
C nullC = null ;
//Note: Struct is value type in D, but composite so no default bool equivalent
logic(theTruth, theLie) ;
logic(zeroReal, NaN) ;
logic(zeroInt, nullArr) ;
logic(nullStr, emptyStr) ;
logic(someC, nullC) ;
}
[edit] E
def logicalOperations(a :boolean, b :boolean) {
return ["and" => a & b,
"or" => a | b,
"not" => !a,
"xor" => a ^ b]
}
Each of these is a method on boolean objects; the above is precisely equivalent to:
def logicalOperations(a :boolean, b :boolean) {
return ["and" => a.and(b),
"or" => a.or(b),
"not" => a.not(),
"xor" => a.xor(b)]
}
If the :boolean guards were removed, these operations would also work on other types, such as sets (& is union and | is intersection; not is not supported).
[edit] Efene
compare_bool = fn (A, B) {
io.format("~p and ~p = ~p~n", [A, B, A and B])
io.format("~p or ~p = ~p~n", [A, B, A or B])
io.format("not ~p = ~p~n", [A, not A])
io.format("~p xor ~p = ~p~n", [A, B, A xor B])
io.format("~n")
}
@public
run = fn () {
compare_bool(true, true)
compare_bool(true, false)
compare_bool(false, true)
compare_bool(false, false)
}
[edit] Erlang
1> true and false.
false
2> false or true.
true
3> true xor false.
true
4> not false.
true
5> not (true and true).
false
[edit] Factor
: logical-operators ( a b -- )
{
[ "xor is: " write xor . ]
[ "and is: " write and . ]
[ "or is: " write or . ]
[ "not is: " write drop not . ]
} 2cleave ;
[edit] FALSE
FALSE uses zero/non-zero for testing False and True. Comparison operators return -1 for True and 0 for False, which work with bitwise operators for logical operations.
1 3=~["unequal, "]?
1 1= 1_=["true is -1, "]?
0~["false is 0, "]?
'm$'a>'z@>&["a < m < z"]?
[edit] Forth
Forth can use bitwise operators if the boolean values are well formed: TRUE (-1) and FALSE (0). 0<> converts an ill-formed flag (zero/non-zero) to a well-formed flag (false/true).
: .bool ( ? -- ) if ." true" else ." false" then ;
: logic ( a b -- ) 0<> swap 0<> swap
cr ." a = " over .bool ." b = " dup .bool
cr ." a and b = " 2dup and .bool
cr ." a or b = " over or .bool
cr ." not a = " 0= .bool ;
[edit] Fortran
In ANSI FORTRAN 66 or later, use LOGICAL data type:
SUBROUTINE PRNLOG(A, B)
LOGICAL A, B
PRINT *, 'a and b is ', A .AND. B
PRINT *, 'a or b is ', A .OR. B
PRINT *, 'not a is ', .NOT. A
C You did not ask, but the following logical operators are also standard
C since ANSI FORTRAN 66
C =======================================================================
C This yields the same results as .EQ., but has lower operator precedence
C and only works with LOGICAL operands:
PRINT *, 'a equivalent to b is ', A .EQV. B
C This yields the same results as .NE., but has lower operator precedence
C and only works with LOGICAL operands (this operation is also commonly
C called "exclusive or"):
PRINT *, 'a not equivalent to b is ', A .NEQV. B
END
[edit] Go
func print_logic(a, b bool) {
fmt.Printf("a and b is %d\n", a && b)
fmt.Printf("a or b is %d\n", a || b)
fmt.Printf("not a is %d\n", !a)
}
[edit] Groovy
def logical = { a, b ->
println """
a AND b = ${a} && ${b} = ${a & b}
a OR b = ${a} || ${b} = ${a | b}
NOT a = ! ${a} = ${! a}
a XOR b = ${a} != ${b} = ${a != b}
a EQV b = ${a} == ${b} = ${a == b}
"""
}
Program:
logical(true, true)
logical(true, false)
logical(false, false)
logical(false, true)
Output:
a AND b = true && true = true a OR b = true || true = true NOT a = ! true = false a XOR b = true != true = false a EQV b = true == true = true a AND b = true && false = false a OR b = true || false = true NOT a = ! true = false a XOR b = true != false = true a EQV b = true == false = false a AND b = false && false = false a OR b = false || false = false NOT a = ! false = true a XOR b = false != false = false a EQV b = false == false = true a AND b = false && true = false a OR b = false || true = true NOT a = ! false = true a XOR b = false != true = true a EQV b = false == true = false
[edit] Haskell
Instead of a function and printing, which is unidiomatic for Haskell, here are the operations in the same style as in Bitwise operations:
a = False
b = True
a_and_b = a && b
a_or_b = a || b
not_a = not a
[edit] HicEst
No logical variables. Nonzero is true, zero is false in logical expressions:
x = value1 /= 0
y = value2 /= 0
NOTx = x == 0
xANDy = x * y
xORy = x + y /= 0
EOR = x /= y
[edit] Io
printLogic := method(a,b,
writeln("a and b is ", a and b)
writeln("a or b is ", a or b)
writeln("not a is ", a not)
)
[edit] Icon and Unicon
Icon/Unicon do not have a native logical or Boolean type; nor do they use Boolean values for flow control. Instead for flow control they use the concept of success (a result is returned) or failure (a signal). For more on this see see Short Circuit Evaluation. Because there is almost no need for Boolean values the concept is somewhat alien.
One likely situation where Boolean values could be encountered is working with an external array of bits/flags. This example attempts to show a solution that would work in such a scenario. Some characteristics would include:
- the ability to work with an entire array of bits
- the ability to test an individual bit for true/false
- need to be careful with automatic type conversions
Of course other characteristics and functionality might be desirable, examples include:
- shifting (based on ishift)
- rotation
- conversion to a (large) integer
- setting a specific bit in the array
Those are left as an exercise for the reader.
There are a couple of choices for implementation. Briefly:
- use of &null and a non-null - this creates problems for negation as not &null can be any or all values
- use of large integers as bit arrays - only signed integers are supported and this complicates preserving array length
- use of strings - a bit wasteful of space
This implementation uses strings as packed arrays of bits. This facilitates easy reading and writing from external sources. While string length is variable it is controlled and doesn't change under negation. The built-in integer bit operations (ior, ixor, iand, ishift) can be utilized under the covers.
[edit] Icon
invocable allPartial Sample Output
procedure main() #: sample demonstrating boolean function use
limit := 4
char2 := char(2)||char(0)
every (i := char(1 to limit)|char2) do {
write(iop := "bnot","( ",image(i)," ) = ",image(iop(i)))
every k := 3 | 10 do {
write("bistrue(",image(i),",",k,") - ", if bistrue(i,k) then "returns" else "fails")
write("bisfalse(",image(i),",",k,") - ", if bisfalse(i,k) then "returns" else "fails")
}
every (j := char(1 to limit)) & (iop := "bor"|"band"|"bxor") do
write(iop,"( ",image(i),", ",image(j)," ) = ",image(iop(i,j)))
}
end
procedure bisfalse(b,p) #: test if bit p (numbered right to left from 1) is false; return b or fails
return boolean_testbit(0,b,p)
end
procedure bistrue(b,p) #: test if bit p is true; return b or fails
return boolean_testbit(1,b,p)
end
procedure bnot(b) #: logical compliment of b (not is a reserved word)
static cs,sc
initial sc := reverse(cs := string(&cset))
if type(b) ~== "string" then runerr(103,b)
return map(b,cs,sc) # en-mass inversion through remapping ordered cset
end
procedure bor(b1,b2) #: logical or
return boolean_op(ior,b1,b2)
end
procedure band(b1,b2) #: logical or
return boolean_op(iand,b1,b2)
end
procedure bxor(b1,b2) #: logical or
return boolean_op(ixor,b1,b2)
end
procedure boolean_testbit(v,b,p) #: (internal) test if bit p is true/false; return b or fail
if not 0 <= integer(p) = p then runerr(101,p)
if type(b) ~== "string" then runerr(103,b)
if v = ishift(ord(b[-p/8-1]), -(p%8)+1) then return b
end
procedure boolean_op(iop,b1,b2) #: boolean helper
local b3,i
static z
initial z := char(0)
if type(b1) ~== "string" then runerr(103,b1)
if type(b2) ~== "string" then runerr(103,b2)
b3 := ""
every i := -1 to -max(*b1,*b2) by -1 do
b3 := char(iop(ord(b1[i]|z),ord(b2[i]|z))) || b3
return b3
end
...
bnot( "\x03" ) = "\xfc"
...
bor( "\x03", "\x01" ) = "\x03"
band( "\x03", "\x01" ) = "\x01"
bxor( "\x03", "\x01" ) = "\x02"
...
bnot( "\x02\x00" ) = "\xfd\xff"
bistrue("\x02\x00",3) - fails
bisfalse("\x02\x00",3) - returns
bistrue("\x02\x00",10) - returns
bisfalse("\x02\x00",10) - fails
bor( "\x02\x00", "\x01" ) = "\x02\x01"
band( "\x02\x00", "\x01" ) = "\x00\x00"
bxor( "\x02\x00", "\x01" ) = "\x02\x01"
...
[edit] Unicon
The Icon solution works in Unicon.
[edit] J
J uses 0 for logical false and 1 for logical true.
aon=: *. , +. , -.@[
The verb defined above is unidiomatic in that when arrays are provided as arguments the results don't seem useful. Definition as seen in the Haskell example would be more natural.
Additional primary logical operators are *: (not-and), +: (not-or), ~: (exclusive-or).
An example more closely following the others on this page (J is interactive so indented lines are user-entered and lines flush left are system outputs):
and=: *.
or=: +.
not=: -.
a=. 0 0 1 1 NB. Work on vectors to show all possible
b=. 0 1 0 1 NB. 2-bit combos at once.
(a and b),(a or b),:not a
0 0 0 1
0 1 1 1
1 1 0 0
[edit] Java
public static void logic(boolean a, boolean b){
System.out.println("a AND b: " + (a && b));
System.out.println("a OR b: " + (a || b));
System.out.println("NOT a: " + (!a));
}
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication).
[edit] JavaScript
function logic(a,b) {
print("a AND b: " + (a && b));
print("a OR b: " + (a || b));
print("NOT a: " + (!a));
}
[edit] Logo
The boolean literals are used as words ("true and "false) when used in a program.
to logic :a :b
(print [a AND b =] and :a :b)
(print [a OR b =] or :a :b)
(print [NOT a =] not :a)
end
AND and OR may have arity greater than two if used in parentheses (and :a :b :c).
[edit] Lua
function logic(a,b)
return a and b, a or b, not a
end
[edit] M4
define(`logical',
`and($1,$2)=eval($1&&$2) or($1,$2)=eval($1||$2) not($1)=eval(!$1)')
logical(1,0)
Output:
and(1,0)=0 or(1,0)=1 not(1)=0
[edit] Mathematica
And[a,b,...]
Or[a,b,...]
Not[a]
And can also be given using the infix operator &&, Or can also be used using the infix operator ||. Not[a] can also be written as !a. Furthermore Mathematica supports:
Xor[a, b,...]
Nand[a, b,...]
Nor[a, b,...]
Xnor[a, b,...]
Note that the functions are not restricted to 2 arguments; any number of arguments are allowed (except for the function Not). All these functions can also be used with infix operators, the characters for that are: \[Xor], \[Nand], \[Nor], and \[Xnor]. Or by typing [escape] [name boolean operator] [escape].
[edit] MAXScript
fn printLogic a b =
(
format "a and b is %\n" (a and b)
format "a or b is %\n" (a or b)
format "not a is %\n" (not a)
)
[edit] Metafont
def tf(expr a) = if a: "true" else: "false" fi enddef;
def test(expr a, b) =
for o = "and", "or":
message tf(a) & " " & o & " " & tf(b);
show a scantokens(o) b;
endfor
message "not " & tf(a);
show not a enddef;
test(true, true);
test(false, false);
test(true, false);
test(false, true);
end
[edit] Modula-3
MODULE Logical EXPORTS Main;
FROM IO IMPORT Put;
FROM Fmt IMPORT Bool;
PROCEDURE Test(a, b: BOOLEAN) =
BEGIN
Put("a AND b is " & Bool(a AND b) & "\n");
Put("a OR b is " & Bool(a OR b) & "\n");
Put("NOT a is " & Bool(NOT a) & "\n");
END Test;
BEGIN
Test(TRUE, FALSE);
END Logical.
[edit] MUMPS
LOGIC(A,B)
WRITE !,A," AND ",B," IS ",A&B
WRITE !,A," OR ",B," IS ",A!B
WRITE !,"NOT ",A," AND ",B," IS ",'(A)&B
WRITE !,"NOT ",A," OR ",B," IS ",'(A)!B
[edit] NewLISP
(define (logic a b)
(print "a and b is: " (and a b) "\n a or b is: " (or a b))
(print "\n not a is: " (not a)))
[edit] Objeck
bundle Default {
class Logic {
function : Main(args : String[]) ~ Nil {
a := true;
b := false;
IO.Console->GetInstance()->Print("a and b is: ")->PrintLine(a & b);
IO.Console->GetInstance()->Print("a or b is: ")->PrintLine(a | b);
IO.Console->GetInstance()->Print("not a is: ")->PrintLine(a <> true);
}
}
}
[edit] OCaml
let print_logic a b =
Printf.printf "a and b is %B\n" (a && b);
Printf.printf "a or b is %B\n" (a || b);
Printf.printf "not a is %B\n" (not a)
[edit] Octave
function test(a, b)
s1 = num2str(a);
s2 = num2str(b);
disp(strcat(s1, " and ", s2, " = ", num2str(a&&b)));
disp(strcat(s1, " or ", s2, " = ", num2str(a||b)));
disp(strcat("not ", s1, " = ", num2str(!a)));
endfunction
% constant true is 1, false is 0
test(true, true);
test(false, false);
test(true, false);
test(false, true);
[edit] Oz
proc {PrintLogic A B}
%% using not short-circuiting standard library functions
{Show {And A B}}
{Show {Or A B}}
{Show {Not A}}
%% using short-circuiting keywords
{Show A andthen B}
{Show A orelse B}
end
[edit] Pascal
procedure printlogic(a, b: boolean);
begin
writeln('a and b is ', a and b);
writeln('a or b is ', a or b);
writeln('not a is', not a);
end;
[edit] Perl
sub show_bool
{
return shift() ? 'true' : 'false', "\n";
}
sub test_logic
{
my ($a, $b) = @_;
print "a and b is ", show_bool $a && $b;
print "a or b is ", show_bool $a || $b;
print "not a is ", show_bool !$a;
print "a xor b is ", show_bool($a xor $b);
}
There are also and, or, and not operators. These are just like &&, ||, and ! (respectively) except for their precedences, which are much lower.
[edit] Perl 6
Perl 6 has an abundance of logical operators for various purposes.
sub logic($a,$b) {
say "$a && $b is ", $a && $b; # short-circuiting
say "$a || $b is ", $a || $b; # short-circuiting
say "$a ^^ $b is ", $a ^^ $b;
say "!$a is ", !$a;
say "$a ?& $b is ", $a ?& $b; # non-short-circuiting
say "$a ?| $b is ", $a ?| $b; # non-short-circuiting
say "$a ?^ $b is ", $a ?^ $b; # non-short-circuiting
say "$a +& $b is ", $a +& $b; # numeric bitwise
say "$a +| $b is ", $a +| $b; # numeric bitwise
say "$a +^ $b is ", $a +^ $b; # numeric bitwise
say "$a ~& $b is ", $a ~& $b; # buffer bitwise
say "$a ~| $b is ", $a ~| $b; # buffer bitwise
say "$a ~^ $b is ", $a ~| $b; # buffer bitwise
say "$a & $b is ", $a & $b; # junctional/autothreading
say "$a | $b is ", $a | $b; # junctional/autothreading
say "$a ^ $b is ", $a ^ $b; # junctional/autothreading
say "$a and $b is ", ($a and $b); # loose short-circuiting
say "$a or $b is ", ($a or $b); # loose short-circuiting
say "$a xor $b is ", ($a xor $b);
say "not $a is ", (not $a);
}
logic(3,10);
Output:
3 && 10 is 10
3 || 10 is 3
3 ^^ 10 is
!3 is 0
3 ?& 10 is 1
3 ?| 10 is 1
3 ?^ 10 is 0
3 +& 10 is 2
3 +| 10 is 11
3 +^ 10 is 9
3 ~& 10 is 1
3 ~| 10 is 30
3 ~^ 10 is 30
3 & 10 is all(3, 10)
3 | 10 is any(3, 10)
3 ^ 10 is one(3, 10)
3 and 10 is 10
3 or 10 is 3
3 xor 10 is
not 3 is 0
[edit] PHP
function print_logic($a, $b)
{
echo "a and b is ", $a && $b ? 'True' : 'False', "\n";
echo "a or b is ", $a || $b ? 'True' : 'False', "\n";
echo "not a is ", ! $a ? 'True' : 'False', "\n";
}
[edit] PicoLisp
(de logic (A B)
(prin "A AND B is ")
(println (and A B))
(prin "A OR B is ")
(println (or A B))
(prin "A XOR B is ")
(println (xor A B))
(prin "NOT A is ")
(println (not A)) )
[edit] PL/I
logical_ops: procedure (t, u);
declare (t, u) bit (1);
put skip list (a & b);
put skip list (a | b);
put skip list (^a);
put skip list (a ^ b); /* exclusive or */
end logical_ops;
[edit] Pop11
define print_logic(a, b);
printf(a and b, 'a and b is %p\n');
printf(a or b, 'a or b is %p\n');
printf(not(a), 'not a is %p\n');
enddefine;
Example usage is:
print_logic(true, false);
[edit] PostScript
/logical{
/a exch def
/b exch def
a b and =
a b or =
a not =
}def
[edit] PowerShell
function Test-Boolean ([bool] $a, [bool] $b) {
Write-Host "A and B: " ($a -and $b)
Write-Host "A or B: " ($a -or $b)
Write-Host "not A: " (-not $a)
Write-Host "not A: " (!$a)
Write-Host "A xor B: " ($a -xor $b)
}
[edit] PureBasic
Procedure LogicDebug(a,b)
Debug a And b
Debug a Or b
Debug Not a
Debug a XOr b
EndProcedure
[edit] Python
def logic(a, b):
print 'a and b:', a and b
print 'a or b:' , a or b
print 'not a:' , not a
Note: Any normal object can be treated as a Boolean in Python. Numeric objects which evaluate to any non-zero value are "True" otherwise they are false. Non-empty strings, lists, tuples and other sequences are "True" otherwise they are false. The pre-defined None object is also treated as "False." In Python 2.3 pre-defined objects named True and False were added to the language; prior to that it was a common convention to include a line: False, True = 0, 1 to use these as names. Custom classes which implement __nonzero__ or __len__ or some other special methods can be implicitly evaluated as Booleans based on those results.
[edit] R
logic <- function(a, b) {
print(a && b)
print(a || b)
print(! a)
}
logic(TRUE, TRUE)
logic(TRUE, FALSE)
logic(FALSE, FALSE)
[edit] Ruby
def logic(a, b)
print 'a and b: ', a && b, "\n"
print 'a or b: ' , a || b, "\n"
print 'not a: ' , !a , "\n"
end
and/or/not are synonymous with &&/||/! albeit with lower precedence.
[edit] Scheme
(define (logic a b)
(display "a and b is ")
(display (and a b))
(newline)
(display "a or b is ")
(display (or a b))
(newline)
(display "not a is ")
(display (not a))
(newline))
[edit] Seed7
const proc: writeLogic (in boolean: a, in boolean: b) is func
begin
writeln("a and b is " <& a and b);
writeln("a or b is " <& a or b);
writeln("not a is " <& not a);
end func;
[edit] Slate
{#/\. #\/. #not} do: [ |:func|
func arity = 1 ifTrue: [inform: 'True ' ; (func as: String) ; ' = ' ; (func sendTo: {True}) printString.
inform: 'False ' ; (func as: String) ; ' = ' ; (func sendTo: {False}) printString.].
func arity = 2
ifTrue: [{{True. True}. {True. False}. {False. True}. {False. False}} do:
[ |:each| inform: each first printString ; (func as: String) ; each second printString ; ' = ' ; (func sendTo: each) printString]]
].
Output:
True/\True = True
True/\False = False
False/\True = False
False/\False = False
True\/True = True
True\/False = True
False\/True = True
False\/False = False
True not = False
False not = True
[edit] Smalltalk
Works with: GNU Smalltalk
|test|
test := [ :a :b |
('%1 %2 %3 = %4' % { a. 'and'. b. (a & b) }) displayNl.
('%1 %2 %3 = %4' % { a. 'or'. b. (a | b) }) displayNl.
('%1 %2 = %3' % {'not'. a. (a not) }) displayNl
].
test value: true value: true.
test value: false value: false.
test value: true value: false.
test value: false value: true.
[edit] Standard ML
fun print_logic (a, b) = (
print ("a and b is " ^ Bool.toString (a andalso b) ^ "\n");
print ("a or b is " ^ Bool.toString (a orelse b) ^ "\n");
print ("not a is " ^ Bool.toString (not a) ^ "\n")
)
[edit] Tcl
proc logic {a b} {
puts "a and b: [expr {$a && $b}]"
puts "a or b: [expr {$a || $b}]"
puts "not a: [expr {!$a}]"
}
[edit] Toka
This is an adaption of the code from the Forth example. Toka provides TRUE/FALSE flags that are the same as the well-formed flags in Forth.
[ 0 <> [ ." true" ] [ ." false"] ifTrueFalse ] is .bool
[ ( a b -- )
cr ." a = " over .bool ." b = " dup .bool
cr ." a and b = " 2dup and .bool
cr ." a or b = " over or .bool
cr ." not a = " 0 = .bool
] is logic
[edit] V
Using stack shuffles.
[mylogic
[get2 [dup] dip swap [dup] dip].
get2 and puts
get2 or puts
swap not puts
pop
].
Using view.
[mylogic
[get2 [a b : a b a b] view].
get2 and puts
get2 or puts
swap not puts
pop
].
Using internal defines
[mylogic [a b] let
a b and puts
a b or puts
a not puts
].
[edit] Visual Basic .NET
Function Test(ByVal a As Boolean, ByVal b As Boolean)
Console.WriteLine("And " & a And b)
Console.WriteLine("Or " & a Or b)
Console.WriteLine("Not " & Not a)
Console.WriteLine("Xor " & a Xor b)
Console.WriteLine("And, short-circuited " & a AndAlso b)
Console.WriteLine("Or, short-circuited " & a OrElse b)
End Function
[edit] XSLT
<xsl:template name="logic">
<xsl:param name="a" select="true()"/>
<xsl:param name="b" select="false()"/>
<fo:block>a and b = <xsl:value-of select="$a and $b"/></fo:block>
<fo:block>a or b = <xsl:value-of select="$a or $b"/></fo:block>
<fo:block>not a = <xsl:value-of select="not($a)"/></fo:block>
</xsl:template>

