Logical operations: Difference between revisions
m (→{{header|J}}) |
Langurmonkey (talk | contribs) |
||
(30 intermediate revisions by 19 users not shown) | |||
Line 12: | Line 12: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang="11l">F logic(a, b) |
||
print(‘a and b: ’(a & b)) |
print(‘a and b: ’(a & b)) |
||
print(‘a or b: ’(a | b)) |
print(‘a or b: ’(a | b)) |
||
print(‘not a: ’(!a))</ |
print(‘not a: ’(!a))</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Line 30: | Line 30: | ||
</pre> |
</pre> |
||
<br>An example: |
<br>An example: |
||
< |
<syntaxhighlight lang="360asm">* Logical operations 04/04/2017 |
||
LOGICAL CSECT |
LOGICAL CSECT |
||
USING LOGICAL,R15 |
USING LOGICAL,R15 |
||
Line 55: | Line 55: | ||
PG DC CL80' ' |
PG DC CL80' ' |
||
YREGS |
YREGS |
||
END LOGICAL</ |
END LOGICAL</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 64: | Line 64: | ||
There are no built-in boolean types; however, supporting the concept in software is trivial. Typically, the zero flag or the carry flag can act as a boolean, with zero being false and nonzero being true. |
There are no built-in boolean types; however, supporting the concept in software is trivial. Typically, the zero flag or the carry flag can act as a boolean, with zero being false and nonzero being true. |
||
< |
<syntaxhighlight lang="6502asm">LDA myBoolean |
||
BNE isTrue |
BNE isTrue |
||
;code that would execute if myBoolean is false, goes here. |
;code that would execute if myBoolean is false, goes here. |
||
Line 70: | Line 70: | ||
isTrue: |
isTrue: |
||
;code that would execute if myBoolean is true, goes here. |
;code that would execute if myBoolean is true, goes here. |
||
RTS </ |
RTS </syntaxhighlight> |
||
===Branches Based On Equality to Zero=== |
===Branches Based On Equality to Zero=== |
||
A logical AND can easily be implemented as a nested if. Here, we'll be executing the following pseudocode. For this example, all variables are one byte in size. |
A logical AND can easily be implemented as a nested if. Here, we'll be executing the following pseudocode. For this example, all variables are one byte in size. |
||
< |
<syntaxhighlight lang="c">if(myValue == 3 && myOtherValue == 5){ |
||
myResult = true; |
myResult = true; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="6502asm">LDA myValue |
||
CMP #3 |
CMP #3 |
||
BNE .skip |
BNE .skip |
||
Line 92: | Line 92: | ||
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult. |
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult. |
||
.skip:</ |
.skip:</syntaxhighlight> |
||
A logical OR is somewhat similar. |
A logical OR is somewhat similar. |
||
< |
<syntaxhighlight lang="c">if(myValue == 3 || myOtherValue == 5){ |
||
myResult = true; |
myResult = true; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="6502asm">LDA myValue |
||
CMP #3 |
CMP #3 |
||
BEQ .doTheThing |
BEQ .doTheThing |
||
Line 113: | Line 113: | ||
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult. |
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult. |
||
.skip:</ |
.skip:</syntaxhighlight> |
||
Logical NOT is the easiest of all; just use the opposite branch condition. |
Logical NOT is the easiest of all; just use the opposite branch condition. |
||
Line 125: | Line 125: | ||
In this example, we'll be testing the bottom 2 bits of the 8-bit variable "Flags", and we want to test if both bits are 1. |
In this example, we'll be testing the bottom 2 bits of the 8-bit variable "Flags", and we want to test if both bits are 1. |
||
< |
<syntaxhighlight lang="6502asm">LDA flags |
||
LSR ;test the rightmost bit. |
LSR ;test the rightmost bit. |
||
BCC .skip |
BCC .skip |
||
Line 133: | Line 133: | ||
;your code for what happens when both of the bottom 2 bits are 1, goes here. |
;your code for what happens when both of the bottom 2 bits are 1, goes here. |
||
.skip:</ |
.skip:</syntaxhighlight> |
||
===Using BIT=== |
===Using BIT=== |
||
If we're testing the top 2 bits of a byte (usually referred to as bit 7 or 6) then there's a special method we can use. The BIT instruction sets the N flag to bit 7 of the tested byte, and the V flag to bit 6 of the tested byte. |
If we're testing the top 2 bits of a byte (usually referred to as bit 7 or 6) then there's a special method we can use. The BIT instruction sets the N flag to bit 7 of the tested byte, and the V flag to bit 6 of the tested byte. |
||
< |
<syntaxhighlight lang="6502asm">BIT myBitFlags |
||
BMI .Bit7Set |
BMI .Bit7Set |
||
BVS .Bit6Set</ |
BVS .Bit6Set</syntaxhighlight> |
||
For this reason, it's a good strategy when designing a bit flags variable to put the bits you'll be testing the most in bit 7 or 6 so that you spend less time checking them. |
For this reason, it's a good strategy when designing a bit flags variable to put the bits you'll be testing the most in bit 7 or 6 so that you spend less time checking them. |
||
Line 146: | Line 146: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun logical-ops (a b) |
||
(progn$ (cw "(and a b) = ~x0~%" (and a b)) |
(progn$ (cw "(and a b) = ~x0~%" (and a b)) |
||
(cw "(or a b) = ~x0~%" (or a b)) |
(cw "(or a b) = ~x0~%" (or a b)) |
||
(cw "(not a) = ~x0~%" (not a))))</ |
(cw "(not a) = ~x0~%" (not a))))</syntaxhighlight> |
||
<br><br> |
<br><br> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">BYTE FUNC Not(BYTE a) |
||
IF a=0 THEN |
IF a=0 THEN |
||
RETURN (1) |
RETURN (1) |
||
Line 176: | Line 176: | ||
OD |
OD |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Logical_operations.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Logical_operations.png Screenshot from Atari 8-bit computer] |
||
Line 193: | Line 193: | ||
providing a direct link between logical and bitwise operations. |
providing a direct link between logical and bitwise operations. |
||
< |
<syntaxhighlight lang="ada">procedure Print_Logic(A : Boolean; B : Boolean) is |
||
begin |
begin |
||
Put_Line("A and B is " & Boolean'Image(A and B)); |
Put_Line("A and B is " & Boolean'Image(A and B)); |
||
Line 199: | Line 199: | ||
Put_Line("A xor B is " & Boolean'Image(A xor B)); |
Put_Line("A xor B is " & Boolean'Image(A xor B)); |
||
Put_Line("not A is " & Boolean'Image(not A)); |
Put_Line("not A is " & Boolean'Image(not A)); |
||
end Print_Logic;</ |
end Print_Logic;</syntaxhighlight> |
||
=={{header|Agda}}== |
=={{header|Agda}}== |
||
===Short version=== |
|||
<lang agda>module AndOrNot where |
|||
<syntaxhighlight lang="agda"> |
|||
module AndOrNot where |
|||
open import Data.Bool |
open import Data.Bool using (Bool ; false ; true ; _∧_ ; _∨_ ; not) |
||
open import Data.Product |
open import Data.Product using (_,_ ; _×_) |
||
test : Bool → Bool → Bool × Bool × Bool |
test : Bool → Bool → Bool × Bool × Bool |
||
test |
test a b = a ∧ b , a ∨ b , not a |
||
</syntaxhighlight> |
|||
e.g. |
e.g. |
||
test true false ⇒ false , true , false |
test true false ⇒ false , true , false |
||
===Long version=== |
|||
<syntaxhighlight lang="agda"> |
|||
module AndOrNot where |
|||
-- This part is to compute the values |
|||
open import Data.Bool using (Bool ; false ; true ; _∧_ ; _∨_ ; not) |
|||
open import Data.Product using (_,_ ; _×_) |
|||
test : Bool → Bool → Bool × Bool × Bool |
|||
test a b = a ∧ b , a ∨ b , not a |
|||
-- This part is to print the result |
|||
open import Agda.Builtin.IO using (IO) |
|||
open import Agda.Builtin.Unit using (⊤) |
|||
open import Data.String using (String ; _++_) |
|||
open import Data.Bool.Show using (show) |
|||
get-and-or-not-str : Bool × Bool × Bool → String |
|||
get-and-or-not-str (t₁ , t₂ , t₃) = |
|||
"a and b: " ++ (show t₁) ++ ", " ++ |
|||
"a or b: " ++ (show t₂) ++ ", " ++ |
|||
"not a: " ++ (show t₃) |
|||
test-str : Bool → Bool → String |
|||
test-str a b = get-and-or-not-str (test a b) |
|||
postulate putStrLn : String → IO ⊤ |
|||
{-# FOREIGN GHC import qualified Data.Text as T #-} |
|||
{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-} |
|||
run : Bool → Bool → IO ⊤ |
|||
run a b = putStrLn (test-str a b) |
|||
main : IO ⊤ |
|||
main = run true false |
|||
-- |
|||
-- This program outputs: |
|||
-- a and b: false, a or b: true, not a: false |
|||
-- |
|||
</syntaxhighlight> |
|||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
< |
<syntaxhighlight lang="aikido"> |
||
function logic(a,b) { |
function logic(a,b) { |
||
println("a AND b: " + (a && b)) |
println("a AND b: " + (a && b)) |
||
Line 223: | Line 275: | ||
println("NOT a: " + (!a)) |
println("NOT a: " + (!a)) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">void |
||
out(integer a, integer b) |
out(integer a, integer b) |
||
{ |
{ |
||
Line 236: | Line 288: | ||
o_integer(!a); |
o_integer(!a); |
||
o_byte('\n'); |
o_byte('\n'); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">PROC print_logic = (BOOL a, b)VOID: |
||
( |
( |
||
# for a 6-7 bit/byte compiler # |
# for a 6-7 bit/byte compiler # |
||
Line 261: | Line 313: | ||
printf(($"not a is "gl$, ¬ a) |
printf(($"not a is "gl$, ¬ a) |
||
printf(($"a not equivalent to b is "gl$, a ≠ b) |
printf(($"a not equivalent to b is "gl$, a ≠ b) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">procedure booleanOperations( logical value a, b ) ; |
||
begin |
begin |
||
Line 277: | Line 329: | ||
write( a, " equ ", b, ": ", a = b ); |
write( a, " equ ", b, ": ", a = b ); |
||
end booleanOperations ;</ |
end booleanOperations ;</syntaxhighlight> |
||
=={{header|Amazing Hopper}}== |
=={{header|Amazing Hopper}}== |
||
<syntaxhighlight lang="amazing hopper"> |
|||
<lang Amazing Hopper> |
|||
#include <hopper.h> |
#include <hopper.h> |
||
Line 310: | Line 362: | ||
exit(0) |
exit(0) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 370: | Line 422: | ||
=={{header|Apex}}== |
=={{header|Apex}}== |
||
< |
<syntaxhighlight lang="java">boolean a = true; |
||
boolean b = false; |
boolean b = false; |
||
System.Debug('a AND b: ' + (a && b)); |
System.Debug('a AND b: ' + (a && b)); |
||
Line 376: | Line 428: | ||
System.Debug('NOT a: ' + (!a)); |
System.Debug('NOT a: ' + (!a)); |
||
System.Debug('a XOR b: ' + (a ^ b)); |
System.Debug('a XOR b: ' + (a ^ b)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
APL represents Boolean values using 1 and 0. This function takes Boolean arguments before it and after it—which may be arrays of Booleans—and returns an array consisting of arg1 AND arg2, arg1 OR arg2, NOT arg1, arg1 NAND arg2, arg1 NOR arg2, and arg1 XOR arg2, in that order. |
APL represents Boolean values using 1 and 0. This function takes Boolean arguments before it and after it—which may be arrays of Booleans—and returns an array consisting of arg1 AND arg2, arg1 OR arg2, NOT arg1, arg1 NAND arg2, arg1 NOR arg2, and arg1 XOR arg2, in that order. |
||
< |
<syntaxhighlight lang="apl"> LOGICALOPS←{(⍺∧⍵)(⍺∨⍵)(~⍺)(⍺⍲⍵)(⍺⍱⍵)(⍺≠⍵)}</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program logicoper.s */ |
/* program logicoper.s */ |
||
Line 521: | Line 573: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">logic: function [a b][ |
||
print ["a AND b =" and? a b] |
print ["a AND b =" and? a b] |
||
print ["a OR b =" or? a b] |
print ["a OR b =" or? a b] |
||
Line 530: | Line 582: | ||
] |
] |
||
logic true false</ |
logic true false</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 539: | Line 591: | ||
=={{header|Asymptote}}== |
=={{header|Asymptote}}== |
||
< |
<syntaxhighlight lang="asymptote">bool a = true; |
||
bool b = false; |
bool b = false; |
||
Line 547: | Line 599: | ||
write(a || b); //(with conditional evaluation of right-hand argument) |
write(a || b); //(with conditional evaluation of right-hand argument) |
||
write(a ^ b); |
write(a ^ b); |
||
write(!a);</ |
write(!a);</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<syntaxhighlight lang="autohotkey">a = 1 |
|||
<lang AutoHotkey>a = 1 |
|||
b = 0 |
b = 0 |
||
msgbox % "a and b is " . (a && b) |
msgbox % "a and b is " . (a && b) |
||
msgbox % "a or b is " . (a || b) |
msgbox % "a or b is " . (a || b) |
||
msgbox % "not a is " . (!a)</ |
msgbox % "not a is " . (!a)</syntaxhighlight> |
||
=={{header|Avail}}== |
=={{header|Avail}}== |
||
Avail provides logical operators to cover all possibilities of a two-argument truth table. (Hence there are 12 entries below, plus the 4 ommitted for the trivial <code>a</code>, <code>b</code>, <code>true</code>, and <code>false</code> = 2^4.) |
Avail provides logical operators to cover all possibilities of a two-argument truth table. (Hence there are 12 entries below, plus the 4 ommitted for the trivial <code>a</code>, <code>b</code>, <code>true</code>, and <code>false</code> = 2^4.) |
||
< |
<syntaxhighlight lang="avail">Method "logic ops_,_" is |
||
[ |
[ |
||
a : boolean; |
a : boolean; |
||
Line 575: | Line 627: | ||
Print: "a xor b: " ++ “a ⊕ b”; // equivalent to a ≠ b |
Print: "a xor b: " ++ “a ⊕ b”; // equivalent to a ≠ b |
||
Print: "a biconditional b: " ++ “a ↔ b”; // equivalent to a = b |
Print: "a biconditional b: " ++ “a ↔ b”; // equivalent to a = b |
||
];</ |
];</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">$ awk '{print "and:"($1&&$2),"or:"($1||$2),"not:"!$1}' |
||
0 0 |
0 0 |
||
and:0 or:0 not:1 |
and:0 or:0 not:1 |
||
Line 586: | Line 638: | ||
and:0 or:1 not:0 |
and:0 or:1 not:0 |
||
1 1 |
1 1 |
||
and:1 or:1 not:0</ |
and:1 or:1 not:0</syntaxhighlight> |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang="axe">Lbl LOGIC |
||
r₁→A |
r₁→A |
||
r₂→B |
r₂→B |
||
Line 595: | Line 647: | ||
Disp "OR:",(A??B)▶Dec,i |
Disp "OR:",(A??B)▶Dec,i |
||
Disp "NOT:",(A?0,1)▶Dec,i |
Disp "NOT:",(A?0,1)▶Dec,i |
||
Return</ |
Return</syntaxhighlight> |
||
Note that unlike [[TI-83 BASIC]], the "and", "or", "xor", and "not(" tokens in Axe are bitwise operators, not logical operators. |
Note that unlike [[TI-83 BASIC]], the "and", "or", "xor", and "not(" tokens in Axe are bitwise operators, not logical operators. |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|Commodore BASIC}}=== |
|||
In Commodore BASIC 'True' is -1 and 'False' is 0. There is no operation for 'exclusive-or'. |
|||
<lang qbasic>10 A = -1 |
|||
20 B = 0 |
|||
30 PRINT A AND B |
|||
40 PRINT A OR B |
|||
50 PRINT (A AND (NOT B)) OR ((NOT A) AND B) |
|||
60 PRINT NOT A</lang> |
|||
{{out}} |
|||
<pre>0 |
|||
-1 |
|||
-1 |
|||
0</pre> |
|||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
< |
<syntaxhighlight lang="basic256">a = true |
||
b = false |
b = false |
||
print a and b |
print a and b |
||
print a or b |
print a or b |
||
print a xor b |
print a xor b |
||
print not a</ |
print not a</syntaxhighlight> |
||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> PROClogic(FALSE, FALSE) |
||
PROClogic(FALSE, TRUE) |
PROClogic(FALSE, TRUE) |
||
PROClogic(TRUE, FALSE) |
PROClogic(TRUE, FALSE) |
||
Line 637: | Line 673: | ||
PRINT a% " EOR " b% " = " a% EOR b% TAB(60); |
PRINT a% " EOR " b% " = " a% EOR b% TAB(60); |
||
PRINT " NOT " a% " = " NOT a% |
PRINT " NOT " a% " = " NOT a% |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 645: | Line 681: | ||
-1 AND -1 = -1 -1 OR -1 = -1 -1 EOR -1 = 0 NOT -1 = 0 |
-1 AND -1 = -1 -1 OR -1 = -1 -1 EOR -1 = 0 NOT -1 = 0 |
||
</pre> |
</pre> |
||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
false = 0 and any non-zero value is true |
|||
<syntaxhighlight lang="qbasic"> |
|||
120 b1 = false 'value of 0 |
|||
130 b2 = true 'value of 1 |
|||
140 print b1 and b2 |
|||
150 print b1 or b2 |
|||
160 print b1 xor b2 |
|||
170 print b1 eqv b2 |
|||
180 print b1 imp b2 |
|||
190 print not b2</syntaxhighlight> |
|||
==={{header|Commodore BASIC}}=== |
|||
In Commodore BASIC the "logical" operators are actually bitwise operators; to enable the proper semantics when they're used for logic, true expressions return -1 (all bits set) and false expressions return 0 (all bits clear). |
|||
<syntaxhighlight lang="qbasic">10 A = -1 |
|||
20 B = 0 |
|||
30 PRINT A AND B |
|||
40 PRINT A OR B |
|||
50 PRINT (A AND (NOT B)) OR ((NOT A) AND B) |
|||
60 PRINT NOT A</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0 |
|||
-1 |
|||
-1 |
|||
0</pre> |
|||
{{works with|Commodore BASIC 7.0}} |
|||
Commodore BASIC version 7 for the C-128 added XOR, but it's a function, and for some reason was written to accept only unsigned (16-bit) numbers. |
|||
<syntaxhighlight lang="basic">70 PRINT XOR(1, 0)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1</pre> |
|||
==={{header|GW-BASIC}}=== |
|||
PC-BASIC has no Boolean type and does not implement Boolean operators. |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|BASICA}} |
|||
<syntaxhighlight lang="qbasic">100 LET FALSE = 0 |
|||
110 LET TRUE = -1 |
|||
120 PRINT TRUE |
|||
130 PRINT FALSE |
|||
120 PRINT TRUE AND FALSE |
|||
150 PRINT TRUE OR FALSE |
|||
160 PRINT TRUE XOR FALSE |
|||
170 PRINT TRUE EQV FALSE |
|||
180 PRINT TRUE IMP FALSE |
|||
190 PRINT NOT TRUE |
|||
200 END</syntaxhighlight> |
|||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 LET A=-1 |
||
110 LET B=0 |
110 LET B=0 |
||
120 PRINT A AND B |
120 PRINT A AND B |
||
Line 655: | Line 741: | ||
160 PRINT 15 BAND 4 |
160 PRINT 15 BAND 4 |
||
170 PRINT 2 BOR 15 |
170 PRINT 2 BOR 15 |
||
180 PRINT (A BOR B)-(A BAND B) ! xor</ |
180 PRINT (A BOR B)-(A BAND B) ! xor</syntaxhighlight> |
||
==={{header|MSX Basic}}=== |
|||
{{works with|MSX BASIC|any}} |
|||
<syntaxhighlight lang="qbasic">120 b1 = false 'value of 0 |
|||
130 b2 = not false 'value of -1 |
|||
140 print b1 and b2 |
|||
150 print b1 or b2 |
|||
160 print b1 xor b2 |
|||
170 print b1 eqv b2 |
|||
180 print b1 imp b2 |
|||
190 print not b2</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
{{works with|QBasic|1.1}} |
{{works with|QBasic|1.1}} |
||
No booleans in BASIC... these are integers. -1 for True 0 for False. |
No booleans in BASIC... these are integers. -1 for True 0 for False. |
||
< |
<syntaxhighlight lang="qbasic">b1 = -1 |
||
b2 = 0 |
b2 = 0 |
||
PRINT b1 AND b2 |
PRINT b1 AND b2 |
||
PRINT b1 OR b2 |
PRINT b1 OR b2 |
||
PRINT NOT b1</ |
PRINT NOT b1</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
< |
<syntaxhighlight lang="yabasic">b1 = true //value of 1 |
||
b2 = false //value of 0 |
b2 = false //value of 0 |
||
print b1 and b2 |
print b1 and b2 |
||
print b1 or b2 |
print b1 or b2 |
||
print not b1</ |
print not b1</syntaxhighlight> |
||
==={{header|QuickBASIC}}=== |
==={{header|QuickBASIC}}=== |
||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
< |
<syntaxhighlight lang="qbasic">SUB logic (a%, b%) 'no booleans in BASIC...these are integers. 1 for true 0 for false. |
||
PRINT a AND b |
PRINT a AND b |
||
PRINT a OR b |
PRINT a OR b |
||
PRINT NOT a |
PRINT NOT a |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
==={{header|Quite BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">120 LET b1 = 0 |
|||
130 LET b2 = -1 |
|||
140 PRINT b1 AND b2 |
|||
150 PRINT b1 OR b2</syntaxhighlight> |
|||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
Line 697: | Line 800: | ||
The following program illustrates the use of these operators: |
The following program illustrates the use of these operators: |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub logicalDemo(b1 As Boolean, b2 As Boolean) |
Sub logicalDemo(b1 As Boolean, b2 As Boolean) |
||
Line 723: | Line 826: | ||
logicalDemo b1, b2 |
logicalDemo b1, b2 |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 775: | Line 878: | ||
POSIX bc has neither Boolean values nor built-in logical operations. |
POSIX bc has neither Boolean values nor built-in logical operations. |
||
Thus one has to write them oneself: |
Thus one has to write them oneself: |
||
< |
<syntaxhighlight lang="bc">/* The following three functions assume 0 is false and 1 is true */ |
||
/* And */ |
/* And */ |
||
Line 799: | Line 902: | ||
"not a: " |
"not a: " |
||
n(a) |
n(a) |
||
}</ |
}</syntaxhighlight> |
||
{{Works with|GNU bc}} |
{{Works with|GNU bc}} |
||
GNU bc's extensions make this task much easier: |
GNU bc's extensions make this task much easier: |
||
< |
<syntaxhighlight lang="bc">define logic_test(a, b) { |
||
print "a and b: ", a && b, "\n" |
print "a and b: ", a && b, "\n" |
||
print "a or b: ", a || b, "\n" |
print "a or b: ", a || b, "\n" |
||
print "not a: ", !a, "\n" |
print "not a: ", !a, "\n" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Binary Lambda Calculus}}== |
|||
Minimal definitions of the logical operations in lambda calculus are: and = <code>\a\b.a b a</code>, or = <code>\a\b.a a b</code>, not = <code>\b\x\y.b y x</code>. In BLC these are <code>00 00 01 01 110 10 110</code>, or = <code>00 00 01 01 110 110 10</code>, not = <code>00 00 00 01 01 1110 10 110</code> respectively. |
|||
=={{header|BQN}}== |
|||
BQN has four logical operators: AND (`∧`), OR (`∨`), NOT (`¬`), XOR (`≠`). The function <code>L</code> lists each of those results in the same order. |
|||
<syntaxhighlight lang="bqn"> L←∧∾∨∾¬∾≠ |
|||
∧∾∨∾¬∾≠ |
|||
0 L 1 |
|||
⟨ 0 1 0 1 ⟩</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
Line 816: | Line 930: | ||
In the example below, the empty string represents 'true' and <code>~</code> represents 'false'. The binary operators <code>&</code> and <code>|</code>, which normally are used as the glue between expressions such as match operations, function definitions and function calls, are used as the logical operators 'and' and 'or', respectively. |
In the example below, the empty string represents 'true' and <code>~</code> represents 'false'. The binary operators <code>&</code> and <code>|</code>, which normally are used as the glue between expressions such as match operations, function definitions and function calls, are used as the logical operators 'and' and 'or', respectively. |
||
< |
<syntaxhighlight lang="bracmat">( ( Logic |
||
= x y |
= x y |
||
. '$arg:(=?x,?y) |
. '$arg:(=?x,?y) |
||
Line 842: | Line 956: | ||
& out$(Logic$(,~)) |
& out$(Logic$(,~)) |
||
& out$(Logic$(~,~)) |
& out$(Logic$(~,~)) |
||
);</ |
);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(x,y)=(,): |
<pre>(x,y)=(,): |
||
Line 865: | Line 979: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">logic = { a, b | |
||
p "a and b: #{ a && b }" |
p "a and b: #{ a && b }" |
||
p "a or b: #{ a || b }" |
p "a or b: #{ a || b }" |
||
p "not a: #{ not a }" |
p "not a: #{ not a }" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">void print_logic(int a, int b) |
||
{ |
{ |
||
printf("a and b is %d\n", a && b); |
printf("a and b is %d\n", a && b); |
||
printf("a or b is %d\n", a || b); |
printf("a or b is %d\n", a || b); |
||
printf("not a is %d\n", !a); |
printf("not a is %d\n", !a); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace LogicalOperations |
namespace LogicalOperations |
||
Line 896: | Line 1,010: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">void print_logic(bool a, bool b) |
||
{ |
{ |
||
std::cout << std::boolalpha; // so that bools are written as "true" and "false" |
std::cout << std::boolalpha; // so that bools are written as "true" and "false" |
||
Line 906: | Line 1,020: | ||
std::cout << "a or b is " << (a || b) << "\n"; |
std::cout << "a or b is " << (a || b) << "\n"; |
||
std::cout << "not a is " << (!a) << "\n"; |
std::cout << "not a is " << (!a) << "\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clipper}}== |
=={{header|Clipper}}== |
||
< |
<syntaxhighlight lang="clipper"> Function Foo( a, b ) |
||
// a and b was defined as .F. (false) or .T. (true) |
// a and b was defined as .F. (false) or .T. (true) |
||
? a .AND. b |
? a .AND. b |
||
Line 915: | Line 1,029: | ||
? .NOT. a, .NOT. b |
? .NOT. a, .NOT. b |
||
Return Nil |
Return Nil |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn logical [a b] |
(defn logical [a b] |
||
(prn (str "a and b is " (and a b))) |
(prn (str "a and b is " (and a b))) |
||
Line 925: | Line 1,039: | ||
(logical true false) |
(logical true false) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Logical operations in COBOL are exactly the same as [[Bitwise operations#COBOL|bitwise operations]]. |
Logical operations in COBOL are exactly the same as [[Bitwise operations#COBOL|bitwise operations]]. |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. print-logic. |
PROGRAM-ID. print-logic. |
||
Line 954: | Line 1,068: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="cfm"><cffunction name = "logic" hint = "Performs basic logical operations"> |
||
<cfargument name = "a" required = "yes" type = "boolean" /> |
<cfargument name = "a" required = "yes" type = "boolean" /> |
||
<cfargument name = "a" required = "yes" type = "boolean" /> |
<cfargument name = "a" required = "yes" type = "boolean" /> |
||
Line 965: | Line 1,079: | ||
NOT 'A' is #!a# |
NOT 'A' is #!a# |
||
</cfoutput> |
</cfoutput> |
||
</cffunction></ |
</cffunction></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun demo-logic (a b) |
||
(mapcar (lambda (op) |
|||
(print "a and b is") (write (and a b)) |
|||
( |
(format t "~a ~a ~a is ~a~%" a op b (eval (list op a b)))) |
||
'(and or))) |
|||
(loop for a in '(nil t) do |
|||
(format t "NOT ~a is ~a~%" a (not a)) |
|||
(loop for b in '(nil t) do (demo-logic a b) (terpri))) |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>NOT NIL is T |
|||
NIL AND NIL is NIL |
|||
NIL OR NIL is NIL |
|||
NIL AND T is NIL |
|||
NIL OR T is T |
|||
NOT T is NIL |
|||
T AND NIL is NIL |
|||
T OR NIL is T |
|||
T AND T is T |
|||
T OR T is T</pre> |
|||
CLISP has <tt>xor</tt>, which can be added to the list of ops in <tt>demo-logic</tt> if using that implementation, but it's not part of the standard. |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void logic(T, U)(T lhs, U rhs) { |
void logic(T, U)(T lhs, U rhs) { |
||
Line 1,007: | Line 1,143: | ||
logic(nullStr, emptyStr); |
logic(nullStr, emptyStr); |
||
logic(someC, nullC); |
logic(someC, nullC); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>'true' is of type 'bool', 'false' is of type 'bool'; |
<pre>'true' is of type 'bool', 'false' is of type 'bool'; |
||
Line 1,035: | Line 1,171: | ||
=={{header|Dc}}== |
=={{header|Dc}}== |
||
< |
<syntaxhighlight lang="dc">[ 1 q ] sT |
||
[ 0=T 0 ] s! |
[ 0=T 0 ] s! |
||
Line 1,055: | Line 1,191: | ||
0 1 lF x |
0 1 lF x |
||
1 0 lF x |
1 0 lF x |
||
1 1 lF x</ |
1 1 lF x</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,066: | Line 1,202: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Delphi supports all logical operators shown in [[#Pascal|§ Pascal]]. |
|||
<lang Delphi>program LogicalOperations; |
|||
Furthermore, the exclusive or operator <tt>xor</tt> is supported: |
|||
<syntaxhighlight lang="delphi"> { exclusive or } |
|||
{$APPTYPE CONSOLE} |
|||
writeLn(A:5, ' xor', B:6, ' yields', A xor B:7);</syntaxhighlight> |
|||
Beware: In Delphi the operators <tt>and</tt>, <tt>or</tt> and <tt>xor</tt> can also refer to [[Bitwise operations#Delphi|bitwise operations]]. |
|||
const |
|||
a = True; |
|||
b = False; |
|||
begin |
|||
Write('a = '); |
|||
Writeln(a); |
|||
Write('b = '); |
|||
Writeln(b); |
|||
Writeln; |
|||
Write('a AND b: '); |
|||
Writeln(a AND b); |
|||
Write('a OR b: '); |
|||
Writeln(a OR b); |
|||
Write('NOT a: '); |
|||
Writeln(NOT a); |
|||
Write('a XOR b: '); |
|||
Writeln(a XOR b); |
|||
end.</lang> |
|||
{{out}} |
|||
<pre>a = TRUE |
|||
b = FALSE |
|||
a AND b: FALSE |
|||
a OR b: TRUE |
|||
NOT a: FALSE |
|||
a XOR b: TRUE</pre> |
|||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">var a := True; |
||
var b := False; |
var b := False; |
||
Line 1,121: | Line 1,227: | ||
Print('a XOR b: '); |
Print('a XOR b: '); |
||
PrintLn(a XOR b);</ |
PrintLn(a XOR b);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a = True |
<pre>a = True |
||
Line 1,132: | Line 1,238: | ||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">var a = true |
||
var b = false |
var b = false |
||
print("a and b is \(a && b)") |
print("a and b is \(a && b)") |
||
print("a or b is \(a || b)") |
print("a or b is \(a || b)") |
||
print("Not a is \(!a)")</ |
print("Not a is \(!a)")</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">showbool a b: |
||
!.( a b or a b and a b xor a b not a ) |
!.( a b or a b and a b xor a b not a ) |
||
for a in [ false true ]: |
for a in [ false true ]: |
||
for b in [ false true ]: |
for b in [ false true ]: |
||
showbool a b</ |
showbool a b</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>true true true true false false |
<pre>true true true true false false |
||
Line 1,153: | Line 1,259: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def logicalOperations(a :boolean, b :boolean) { |
||
return ["and" => a & b, |
return ["and" => a & b, |
||
"or" => a | b, |
"or" => a | b, |
||
"not" => !a, |
"not" => !a, |
||
"xor" => a ^ b] |
"xor" => a ^ b] |
||
}</ |
}</syntaxhighlight> |
||
Each of these is a method on [http://wiki.erights.org/wiki/Boolean boolean objects]; the above is precisely equivalent to: |
Each of these is a method on [http://wiki.erights.org/wiki/Boolean boolean objects]; the above is precisely equivalent to: |
||
< |
<syntaxhighlight lang="e">def logicalOperations(a :boolean, b :boolean) { |
||
return ["and" => a.and(b), |
return ["and" => a.and(b), |
||
"or" => a.or(b), |
"or" => a.or(b), |
||
"not" => a.not(), |
"not" => a.not(), |
||
"xor" => a.xor(b)] |
"xor" => a.xor(b)] |
||
}</ |
}</syntaxhighlight> |
||
If the <code>:boolean</code> guards were removed, these operations would also work on other types, such as sets (& is union and | is intersection; <code>not</code> is not supported). |
If the <code>:boolean</code> guards were removed, these operations would also work on other types, such as sets (& is union and | is intersection; <code>not</code> is not supported). |
||
Line 1,173: | Line 1,279: | ||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<syntaxhighlight lang="text"> |
|||
<lang>func logic a b . . |
|||
proc logic a b . . |
|||
if a = 1 and b = 1 |
|||
r1 = 1 |
|||
. |
|||
. |
|||
if a = 1 or b = 1 |
|||
if a = 1 or b = 1 |
|||
r2 = 1 |
|||
. |
|||
. |
|||
if a = 0 |
|||
r3 = 1 |
|||
. |
|||
. |
|||
print r1 & " " & r2 & " " & r3 |
|||
print r1 & " " & r2 & " " & r3 |
|||
. |
. |
||
logic 0 0 |
|||
logic 0 1 |
|||
logic 1 0 |
|||
logic 1 1 |
|||
</syntaxhighlight> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
<syntaxhighlight lang="ecl"> |
|||
<lang ECL> |
|||
LogicalOperations(BOOLEAN A,BOOLEAN B) := FUNCTION |
LogicalOperations(BOOLEAN A,BOOLEAN B) := FUNCTION |
||
ANDit := A AND B; |
ANDit := A AND B; |
||
Line 1,210: | Line 1,318: | ||
LogicalOperations(TRUE,TRUE); |
LogicalOperations(TRUE,TRUE); |
||
LogicalOperations(1>2,1=1); //Boolean expressions are also valid here |
LogicalOperations(1>2,1=1); //Boolean expressions are also valid here |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
< |
<syntaxhighlight lang="efene">compare_bool = fn (A, B) { |
||
io.format("~p and ~p = ~p~n", [A, B, A and 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("~p or ~p = ~p~n", [A, B, A or B]) |
||
Line 1,229: | Line 1,337: | ||
compare_bool(false, false) |
compare_bool(false, false) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x: |
ELENA 4.x: |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
public program() |
public program() |
||
Line 1,244: | Line 1,352: | ||
console.printLine("Not a is ", a.Inverted); |
console.printLine("Not a is ", a.Inverted); |
||
console.printLine("a xor b is ", a ^^ b) |
console.printLine("a xor b is ", a ^^ b) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,255: | Line 1,363: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Elixir also provides three boolean operators: <code>or</code>, <code>and</code> and <code>not</code>. These operators are strict in the sense that they expect a boolean (<code>true</code> or <code>false</code>) as their first argument: |
Elixir also provides three boolean operators: <code>or</code>, <code>and</code> and <code>not</code>. These operators are strict in the sense that they expect a boolean (<code>true</code> or <code>false</code>) as their first argument: |
||
< |
<syntaxhighlight lang="elixir">iex(1)> true and false |
||
false |
false |
||
iex(2)> false or true |
iex(2)> false or true |
||
true |
true |
||
iex(3)> not false |
iex(3)> not false |
||
true</ |
true</syntaxhighlight> |
||
<code>or</code> and <code>and</code> are short-circuit operators. They only execute the right side if the left side is not enough to determine the result: |
<code>or</code> and <code>and</code> are short-circuit operators. They only execute the right side if the left side is not enough to determine the result: |
||
Besides these boolean operators, Elixir also provides <code>||</code>, <code>&&</code> and <code>!</code> which accept arguments of any type. For these operators, all values except <code>false</code> and <code>nil</code> will evaluate to true: |
Besides these boolean operators, Elixir also provides <code>||</code>, <code>&&</code> and <code>!</code> which accept arguments of any type. For these operators, all values except <code>false</code> and <code>nil</code> will evaluate to true: |
||
< |
<syntaxhighlight lang="elixir">(28)> nil || 23 |
||
23 |
23 |
||
iex(29)> [] || false |
iex(29)> [] || false |
||
Line 1,277: | Line 1,385: | ||
true |
true |
||
iex(34)> ! 3.14 |
iex(34)> ! 3.14 |
||
false</ |
false</syntaxhighlight> |
||
As a rule of thumb, use <code>and</code>, <code>or</code> and <code>not</code> when you are expecting booleans. If any of the arguments are non-boolean, use <code>&&</code>, <code>||</code> and <code>!</code>. |
As a rule of thumb, use <code>and</code>, <code>or</code> and <code>not</code> when you are expecting booleans. If any of the arguments are non-boolean, use <code>&&</code>, <code>||</code> and <code>!</code>. |
||
=={{header|Elm}}== |
=={{header|Elm}}== |
||
<syntaxhighlight lang="elm"> |
|||
<lang Elm> |
|||
--Open cmd and elm-repl and directly functions can be created |
--Open cmd and elm-repl and directly functions can be created |
||
Line 1,298: | Line 1,406: | ||
--Output will be False, True and True of type Boolean! |
--Output will be False, True and True of type Boolean! |
||
--end |
--end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
fun logicOperations = void by logic a, logic b |
|||
writeLine("=== input values are " + a + ", " + b + " ===") |
|||
writeLine("a and b: " + (a and b)) |
|||
writeLine(" a or b: " + (a or b)) |
|||
writeLine(" not a: " + (not a)) |
|||
end |
|||
logicOperations(false, false) |
|||
logicOperations(false, true) |
|||
logicOperations(true, false) |
|||
logicOperations(true, true) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
=== input values are ⊥, ⊥ === |
|||
a and b: ⊥ |
|||
a or b: ⊥ |
|||
not a: ⊤ |
|||
=== input values are ⊥, ⊤ === |
|||
a and b: ⊥ |
|||
a or b: ⊤ |
|||
not a: ⊤ |
|||
=== input values are ⊤, ⊥ === |
|||
a and b: ⊥ |
|||
a or b: ⊤ |
|||
not a: ⊥ |
|||
=== input values are ⊤, ⊤ === |
|||
a and b: ⊤ |
|||
a or b: ⊤ |
|||
not a: ⊥ |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">1> true and false. |
||
false |
false |
||
2> false or true. |
2> false or true. |
||
Line 1,310: | Line 1,451: | ||
true |
true |
||
5> not (true and true). |
5> not (true and true). |
||
false</ |
false</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">procedure print_logic(integer a, integer b) |
||
printf(1,"a and b is %d\n", a and b) |
printf(1,"a and b is %d\n", a and b) |
||
printf(1,"a or b is %d\n", a or b) |
printf(1,"a or b is %d\n", a or b) |
||
printf(1,"a xor b is %d\n", a xor b) |
printf(1,"a xor b is %d\n", a xor b) |
||
printf(1,"not a is %d\n", not a) |
printf(1,"not a is %d\n", not a) |
||
end procedure</ |
end procedure</syntaxhighlight> |
||
=={{header|Excel}}== |
=={{header|Excel}}== |
||
Line 1,324: | Line 1,465: | ||
If the values are typed in cells A1 and B1, type in the following in cell C1 |
If the values are typed in cells A1 and B1, type in the following in cell C1 |
||
< |
<syntaxhighlight lang="excel"> |
||
=CONCATENATE($A1, " AND ", $B1, " is ", AND($A1,$B1)) |
=CONCATENATE($A1, " AND ", $B1, " is ", AND($A1,$B1)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
In D1 |
In D1 |
||
< |
<syntaxhighlight lang="excel"> |
||
=CONCATENATE($A1, " OR ", $B1, " is ", OR($A1,$B1)) |
=CONCATENATE($A1, " OR ", $B1, " is ", OR($A1,$B1)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
In E1 |
In E1 |
||
< |
<syntaxhighlight lang="excel"> |
||
=CONCATENATE(" NOT ", $A1, " is ", NOT($A1)) |
=CONCATENATE(" NOT ", $A1, " is ", NOT($A1)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let printLogic a b = |
||
printfn "a and b is %b" (a && b) |
printfn "a and b is %b" (a && b) |
||
printfn "a or b is %b" (a || b) |
printfn "a or b is %b" (a || b) |
||
printfn "Not a is %b" (not a) |
printfn "Not a is %b" (not a) |
||
// The not-equals operator has the same effect as XOR on booleans. |
// The not-equals operator has the same effect as XOR on booleans. |
||
printfn "a exclusive-or b is %b" (a <> b)</ |
printfn "a exclusive-or b is %b" (a <> b)</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">: logical-operators ( a b -- ) |
||
{ |
{ |
||
[ "xor is: " write xor . ] |
[ "xor is: " write xor . ] |
||
Line 1,355: | Line 1,496: | ||
[ "or is: " write or . ] |
[ "or is: " write or . ] |
||
[ "not is: " write drop not . ] |
[ "not is: " write drop not . ] |
||
} 2cleave ;</ |
} 2cleave ;</syntaxhighlight> |
||
=={{header|FALSE}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="false">1 3=~["unequal, "]? |
||
1 1= 1_=["true is -1, "]? |
1 1= 1_=["true is -1, "]? |
||
0~["false is 0, "]? |
0~["false is 0, "]? |
||
'm$'a>'z@>&["a < m < z"]?</ |
'm$'a>'z@>&["a < m < z"]?</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,388: | Line 1,529: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|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). |
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). |
||
< |
<syntaxhighlight lang="forth">: .bool ( ? -- ) if ." true" else ." false" then ; |
||
: logic ( a b -- ) 0<> swap 0<> swap |
: logic ( a b -- ) 0<> swap 0<> swap |
||
cr ." a = " over .bool ." b = " dup .bool |
cr ." a = " over .bool ." b = " dup .bool |
||
cr ." a and b = " 2dup and .bool |
cr ." a and b = " 2dup and .bool |
||
cr ." a or b = " over or .bool |
cr ." a or b = " over or .bool |
||
cr ." not a = " 0= .bool ;</ |
cr ." not a = " 0= .bool ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ANSI FORTRAN 66 or later, use LOGICAL data type: |
In ANSI FORTRAN 66 or later, use LOGICAL data type: |
||
< |
<syntaxhighlight lang="fortran"> SUBROUTINE PRNLOG(A, B) |
||
LOGICAL A, B |
LOGICAL A, B |
||
PRINT *, 'a and b is ', A .AND. B |
PRINT *, 'a and b is ', A .AND. B |
||
Line 1,419: | Line 1,560: | ||
C called "exclusive or"): |
C called "exclusive or"): |
||
PRINT *, 'a not equivalent to b is ', A .NEQV. B |
PRINT *, 'a not equivalent to b is ', A .NEQV. B |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Free Pascal}}== |
|||
''See [[#Delphi|Delphi]]'' |
|||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink">logical[a,b] := |
||
{ |
{ |
||
println["$a and $b is " + (a and b)] |
println["$a and $b is " + (a and b)] |
||
Line 1,430: | Line 1,574: | ||
println["$a nor $b is " + (a nor b)] |
println["$a nor $b is " + (a nor b)] |
||
println["not $a is " + (not a)] |
println["not $a is " + (not a)] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
< |
<syntaxhighlight lang="funl">def logical( a, b ) = println( """ |
||
a and b = ${a and b} |
a and b = ${a and b} |
||
a or b = ${a or b} |
a or b = ${a or b} |
||
Line 1,440: | Line 1,584: | ||
""" ) |
""" ) |
||
for i <- [false, true], j <- [false, true] do logical( i, j )</ |
for i <- [false, true], j <- [false, true] do logical( i, j )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,470: | Line 1,614: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">window 1, @"Logical Operations", (0,0,480,270) |
||
Boolean a, b |
Boolean a, b |
||
Line 1,500: | Line 1,644: | ||
HandleEvents |
HandleEvents |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
Line 1,523: | Line 1,667: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">Logical := function(a, b) |
||
return [ a or b, a and b, not a ]; |
return [ a or b, a and b, not a ]; |
||
end; |
end; |
||
Line 1,537: | Line 1,681: | ||
Logical(false, false); |
Logical(false, false); |
||
# [ false, false, true ]</ |
# [ false, false, true ]</syntaxhighlight> |
||
=={{header|gecho}}== |
=={{header|gecho}}== |
||
<lang |
<syntaxhighlight lang="gecho">3 4 and</syntaxhighlight> |
||
3&&4 |
3&&4 |
||
<lang |
<syntaxhighlight lang="gecho">1 2 or</syntaxhighlight> |
||
1||2 |
1||2 |
||
=={{header|Genie}}== |
=={{header|Genie}}== |
||
< |
<syntaxhighlight lang="genie">[indent=4] |
||
/* |
/* |
||
Logical operations in Genie |
Logical operations in Genie |
||
Line 1,561: | Line 1,705: | ||
a:bool = bool.parse(args[1]) |
a:bool = bool.parse(args[1]) |
||
b:bool = bool.parse(args[2]) |
b:bool = bool.parse(args[2]) |
||
logicals(a, b)</ |
logicals(a, b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,571: | Line 1,715: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">func printLogic(a, b bool) { |
||
fmt.Println("a and b is", a && b) |
fmt.Println("a and b is", a && b) |
||
fmt.Println("a or b is", a || b) |
fmt.Println("a or b is", a || b) |
||
fmt.Println("not a is", !a) |
fmt.Println("not a is", !a) |
||
}</ |
}</syntaxhighlight> |
||
Other operators that work on type bool are == and !=. == corresponds to the logical operation of equivalence. != corresponds to exclusive or. |
Other operators that work on type bool are == and !=. == corresponds to the logical operation of equivalence. != corresponds to exclusive or. |
||
Bitwise operators come into play when you have to work with byte- or bit-level data. |
Bitwise operators come into play when you have to work with byte- or bit-level data. |
||
::< |
::<syntaxhighlight lang="go">package main |
||
// stackoverflow.com/questions/28432398/difference-between-some-operators-golang |
// stackoverflow.com/questions/28432398/difference-between-some-operators-golang |
||
import "fmt" |
import "fmt" |
||
Line 1,613: | Line 1,757: | ||
// 3 &^ 6 = 00000001 = 1 |
// 3 &^ 6 = 00000001 = 1 |
||
fmt.Println(3 &^ 6) |
fmt.Println(3 &^ 6) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">def logical = { a, b -> |
||
println """ |
println """ |
||
a AND b = ${a} && ${b} = ${a & b} |
a AND b = ${a} && ${b} = ${a & b} |
||
Line 1,624: | Line 1,768: | ||
a EQV b = ${a} == ${b} = ${a == b} |
a EQV b = ${a} == ${b} = ${a == b} |
||
""" |
""" |
||
}</ |
}</syntaxhighlight> |
||
Program: |
Program: |
||
< |
<syntaxhighlight lang="groovy">[true, false].each { a -> [true, false].each { b-> logical(a, b) } }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,658: | Line 1,802: | ||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
< |
<syntaxhighlight lang="visualfoxpro">PROCEDURE Foo( a, b ) |
||
// a and b was defined as .F. (false) or .T. (true) |
// a and b was defined as .F. (false) or .T. (true) |
||
? a .AND. b |
? a .AND. b |
||
? a .OR. b |
? a .OR. b |
||
? ! a, ! b |
? ! a, ! b |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 1,669: | Line 1,813: | ||
Instead of a function and printing, which is unidiomatic for Haskell, here are the operations in the same style as in [[Bitwise operations]]: |
Instead of a function and printing, which is unidiomatic for Haskell, here are the operations in the same style as in [[Bitwise operations]]: |
||
< |
<syntaxhighlight lang="haskell">a = False |
||
b = True |
b = True |
||
Line 1,677: | Line 1,821: | ||
a_xor_b = a /= b |
a_xor_b = a /= b |
||
a_nxor_b = a == b |
a_nxor_b = a == b |
||
a_implies_b = a <= b -- sic! </ |
a_implies_b = a <= b -- sic! </syntaxhighlight> |
||
(&&) and (||) are lazy on the second argument and therefore this operations are not symmetric: |
(&&) and (||) are lazy on the second argument and therefore this operations are not symmetric: |
||
< |
<syntaxhighlight lang="haskell">*Main > False && undefined |
||
False |
False |
||
Prelude> undefined && False |
Prelude> undefined && False |
||
Line 1,687: | Line 1,831: | ||
True |
True |
||
Prelude> undefined || True |
Prelude> undefined || True |
||
*** Exception: Prelude.undefined</ |
*** Exception: Prelude.undefined</syntaxhighlight> |
||
(<=), (<), (>=) and (>) on the other hand are strict: |
(<=), (<), (>=) and (>) on the other hand are strict: |
||
< |
<syntaxhighlight lang="haskell">Prelude> False <= undefined |
||
*** Exception: Prelude.undefined |
*** Exception: Prelude.undefined |
||
Prelude> undefined <= True |
Prelude> undefined <= True |
||
Line 1,696: | Line 1,840: | ||
*** Exception: Prelude.undefined |
*** Exception: Prelude.undefined |
||
Prelude> undefined < False |
Prelude> undefined < False |
||
*** Exception: Prelude.undefined</ |
*** Exception: Prelude.undefined</syntaxhighlight> |
||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<syntaxhighlight lang="hexiscript">fun logic a b |
||
println "a and b = " + (a && b) |
println "a and b = " + (a && b) |
||
println "a or b = " + (a || b) |
println "a or b = " + (a || b) |
||
println " not a = " + (!a) |
println " not a = " + (!a) |
||
endfun</ |
endfun</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
No logical variables. Nonzero is true, zero is false in logical expressions: |
No logical variables. Nonzero is true, zero is false in logical expressions: |
||
< |
<syntaxhighlight lang="hicest"> x = value1 /= 0 |
||
y = value2 /= 0 |
y = value2 /= 0 |
||
NOTx = x == 0 |
NOTx = x == 0 |
||
xANDy = x * y |
xANDy = x * y |
||
xORy = x + y /= 0 |
xORy = x + y /= 0 |
||
EOR = x /= y </ |
EOR = x /= y </syntaxhighlight> |
||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
< |
<syntaxhighlight lang="holyc">U0 PrintLogic(Bool a, Bool b) { |
||
Print("a and b is %d\n", a && b); |
Print("a and b is %d\n", a && b); |
||
Print("a or b is %d\n", a || b); |
Print("a or b is %d\n", a || b); |
||
Line 1,722: | Line 1,866: | ||
} |
} |
||
PrintLogic(TRUE, FALSE);</ |
PrintLogic(TRUE, FALSE);</syntaxhighlight> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
< |
<syntaxhighlight lang="clojure">(defn logic [a b] |
||
(print "a and b:" (and a b)) |
(print "a and b:" (and a b)) |
||
(print "a or b:" (or a b)) |
(print "a or b:" (or a b)) |
||
(print "not a:" (not a)))</ |
(print "not a:" (not a)))</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 1,751: | Line 1,895: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="icon">invocable all |
||
procedure main() #: sample demonstrating boolean function use |
procedure main() #: sample demonstrating boolean function use |
||
Line 1,812: | Line 1,956: | ||
b3 := char(iop(ord(b1[i]|z),ord(b2[i]|z))) || b3 |
b3 := char(iop(ord(b1[i]|z),ord(b2[i]|z))) || b3 |
||
return b3 |
return b3 |
||
end</ |
end</syntaxhighlight> |
||
{{out|Partial Sample Output:}} |
{{out|Partial Sample Output:}} |
||
Line 1,831: | Line 1,975: | ||
bxor( "\x02\x00", "\x01" ) = "\x02\x01" |
bxor( "\x02\x00", "\x01" ) = "\x02\x01" |
||
...</pre> |
...</pre> |
||
=={{Header|Insitux}}== |
|||
Insitux treats all non-<code>null</code>/<code>false</code> values as truthy, which is illustrated by using placeholder keywords <code>:a</code> and <code>:b</code> in place of just <code>true</code> to see how the different operations process them. <code>and</code> and <code>or</code> can accept more than two arguments but this is not demonstrated here. |
|||
<syntaxhighlight lang="insitux"> |
|||
(let pad (comp str (pad-right " " 10))) |
|||
(print "a b | (and a b) (or a b) (not a) (xor a b)") |
|||
(print (str* "-" 20) "+" (str* "-" 40)) |
|||
(join "\n" |
|||
(for a [false :a] |
|||
b [false :b] |
|||
(... str (pad a) (pad b) "| " |
|||
(for op [and or not xor] |
|||
(pad (if (= op not) (op a) (op a b))))))) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
a b | (and a b) (or a b) (not a) (xor a b) |
|||
--------------------+---------------------------------------- |
|||
false false | false null true false |
|||
false :b | false :b true :b |
|||
:a false | false :a false :a |
|||
:a :b | true :a false false |
|||
</pre> |
|||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">printLogic := method(a,b, |
||
writeln("a and b is ", a and b) |
writeln("a and b is ", a and b) |
||
writeln("a or b is ", a or b) |
writeln("a or b is ", a or b) |
||
writeln("not a is ", a not) |
writeln("not a is ", a not) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
J uses 0 for logical false and 1 for logical true. |
J uses 0 for logical false and 1 for logical true. |
||
< |
<syntaxhighlight lang="j"> aon=: *.`+.`(-.@[)`:0</syntaxhighlight> |
||
Given boolean arguments, <code>*.</code> is logical and, <code>+.</code> is logical or, and <code>-.</code>is logical not. |
Given boolean arguments, <code>*.</code> is logical and, <code>+.</code> is logical or, and <code>-.</code>is logical not. |
||
Additional primary logical operators include <code>*:</code> (not-and), <code>+:</code> (not-or), <code>~:</code> (exclusive-or) and <code><:</code> (logical implication). |
Additional primary logical operators include <code>*:</code> (not-and), <code>+:</code> (not-or), <code>~:</code> (exclusive-or) and <code><:</code> (logical implication). |
||
<syntaxhighlight lang="j"> |
|||
<lang j> |
|||
a=: 0 0 1 1 NB. Work on vectors to show all possible |
a=: 0 0 1 1 NB. Work on vectors to show all possible |
||
b=: 0 1 0 1 NB. 2-bit combos at once. |
b=: 0 1 0 1 NB. 2-bit combos at once. |
||
Line 1,853: | Line 2,026: | ||
0 0 0 1 |
0 0 0 1 |
||
0 1 1 1 |
0 1 1 1 |
||
1 1 0 0</ |
1 1 0 0</syntaxhighlight> |
||
An alternate approach, based on a probabilistic interpretation, uses <code>*</code> for logical and, <code>-.</code> for logical negation and derives the others: <code>(*&.-.)</code> for logical or, <code>(-.@*)</code> for not-and, <code>(-.@*&.-.)</code> for not-or, <code>(* *&.-. -.@*&.-.)</code> for exclusive or, and <code>(*&.-. -.)~</code> for logical implication. You get the same results for simple truth values this way, but you also get consistent treatment for values between 0 and 1. |
An alternate approach, based on a probabilistic interpretation, uses <code>*</code> for logical and, <code>-.</code> for logical negation and derives the others: <code>(*&.-.)</code> for logical or, <code>(-.@*)</code> for not-and, <code>(-.@*&.-.)</code> for not-or, <code>(* *&.-. -.@*&.-.)</code> for exclusive or, and <code>(*&.-. -.)~</code> for logical implication. You get the same results for simple truth values this way, but you also get consistent treatment for values between 0 and 1. |
||
Line 1,859: | Line 2,032: | ||
That said, J also supports truth valued operations on the binary representations of integers. (This is the concept of "packed binary", roughly speaking). For example <code>2b10001 b.</code> is '''and''', <code>2b10111 b.</code> is '''or''', <code>2b11110 b.</code> is '''nand''', etc. (the last four bits of the control argument to <code>b.</code> represent the desired binary truth table, while the prefix of that control argument in these examples specifies "packed binary"). Thus: |
That said, J also supports truth valued operations on the binary representations of integers. (This is the concept of "packed binary", roughly speaking). For example <code>2b10001 b.</code> is '''and''', <code>2b10111 b.</code> is '''or''', <code>2b11110 b.</code> is '''nand''', etc. (the last four bits of the control argument to <code>b.</code> represent the desired binary truth table, while the prefix of that control argument in these examples specifies "packed binary"). Thus: |
||
< |
<syntaxhighlight lang="j"> (2b10001 b. table/~i.4);(2b10110 b. table/~i.4);<2b10000 b. table/~i.4 |
||
┌───────────────┬───────────────┬───────────────┐ |
┌───────────────┬───────────────┬───────────────┐ |
||
│┌─────┬───────┐│┌─────┬───────┐│┌─────┬───────┐│ |
│┌─────┬───────┐│┌─────┬───────┐│┌─────┬───────┐│ |
||
Line 1,869: | Line 2,042: | ||
││3 │0 1 2 3│││3 │3 2 1 0│││3 │0 0 0 0││ |
││3 │0 1 2 3│││3 │3 2 1 0│││3 │0 0 0 0││ |
||
│└─────┴───────┘│└─────┴───────┘│└─────┴───────┘│ |
│└─────┴───────┘│└─────┴───────┘│└─────┴───────┘│ |
||
└───────────────┴───────────────┴───────────────┘</ |
└───────────────┴───────────────┴───────────────┘</syntaxhighlight> |
||
=={{header|Jakt}}== |
|||
<syntaxhighlight lang="jakt"> |
|||
fn logical_operations(anon a: bool, anon b: bool) { |
|||
println("a and b is {}", a and b) |
|||
println("a or b is {}", a or b) |
|||
println("not a is {}", not a) |
|||
} |
|||
fn main() { |
|||
let a = true |
|||
let b = false |
|||
logical_operations(a, b) |
|||
// Extra operations |
|||
println("a equals b is {}", a == b) |
|||
println("a xor b is {}", (a ^ b) == true) // == true ensures bool |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public static void logic(boolean a, boolean b){ |
||
System.out.println("a AND b: " + (a && b)); |
System.out.println("a AND b: " + (a && b)); |
||
System.out.println("a OR b: " + (a || b)); |
System.out.println("a OR b: " + (a || b)); |
||
System.out.println("NOT a: " + (!a)); |
System.out.println("NOT a: " + (!a)); |
||
}</ |
}</syntaxhighlight> |
||
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication). |
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication). |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">function logic(a,b) { |
||
print("a AND b: " + (a && b)); |
print("a AND b: " + (a && b)); |
||
print("a OR b: " + (a || b)); |
print("a OR b: " + (a || b)); |
||
print("NOT a: " + (!a)); |
print("NOT a: " + (!a)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,892: | Line 2,084: | ||
In addition to the basic logical operators, jq has <tt>any</tt> and <tt>all</tt> filters. Versions of jq since 1.4 also have extended versions of these for working efficiently with streams. |
In addition to the basic logical operators, jq has <tt>any</tt> and <tt>all</tt> filters. Versions of jq since 1.4 also have extended versions of these for working efficiently with streams. |
||
< |
<syntaxhighlight lang="jq">def logic(a; b): |
||
"\(a) and \(b) => \(a and b)", |
"\(a) and \(b) => \(a and b)", |
||
"\(a) or \(b) => \(a or b)", |
"\(a) or \(b) => \(a or b)", |
||
"\(a) | not => \(a | not)", |
"\(a) | not => \(a | not)", |
||
"if \(a) then true else false end => \(if a then true else false end)" ;</ |
"if \(a) then true else false end => \(if a then true else false end)" ;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="jq"> (false, null, []) as $a |
||
| (false, null, {}) as $b |
| (false, null, {}) as $b |
||
| logic( $a; $b )</ |
| logic( $a; $b )</syntaxhighlight> |
||
<div style="overflow:scroll; height:200px;"> |
<div style="overflow:scroll; height:200px;"> |
||
< |
<syntaxhighlight lang="sh">$ jq -n -r -f logical_operations.jq |
||
false and false => false |
false and false => false |
||
false or false => false |
false or false => false |
||
Line 1,938: | Line 2,130: | ||
[] or {} => true |
[] or {} => true |
||
[] | not => false |
[] | not => false |
||
if [] then true else false end => true</ |
if [] then true else false end => true</syntaxhighlight></div> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">using Printf |
||
function exerciselogic(a::Bool, b::Bool) |
function exerciselogic(a::Bool, b::Bool) |
||
Line 1,957: | Line 2,149: | ||
println(exerciselogic(a, b)) |
println(exerciselogic(a, b)) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,975: | Line 2,167: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Similar style to FreeBASIC entry: |
Similar style to FreeBASIC entry: |
||
<syntaxhighlight lang="kotlin"> |
|||
<lang scala>// version 1.0.6 |
|||
fun logicalDemo(b1: Boolean, b2: Boolean) { |
fun logicalDemo(b1: Boolean, b2: Boolean) { |
||
println("b1 |
println("b1 = $b1") |
||
println("b2 |
println("b2 = $b2") |
||
println(" |
println("non-short-circuiting operators:") |
||
println("b1 |
println("b1 and b2 = ${b1 and b2}") |
||
println("b1 |
println("b1 or b2 = ${b1 or b2}") |
||
println(" |
println("b1 xor b2 = ${b1 xor b2}") |
||
println("b1 |
println("not b1 = ${!b1}") |
||
println(" |
println("short-circuiting operators:") |
||
println("b1 && b2 = ${b1 && b2}") |
|||
println("b1 || b2 = ${b1 || b2}") |
|||
println() |
println() |
||
} |
} |
||
fun main( |
fun main() { |
||
logicalDemo(true, true) |
logicalDemo(true, true) |
||
logicalDemo(true, false) |
logicalDemo(true, false) |
||
logicalDemo(false, true) |
|||
logicalDemo(false, false) |
logicalDemo(false, false) |
||
}</syntaxhighlight> |
|||
logicalDemo(false, true) |
|||
}</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
b1 |
b1 = true |
||
b2 |
b2 = true |
||
non-short-circuiting operators: |
|||
b1 and b2 = true |
|||
b1 |
b1 and b2 = true |
||
b1 |
b1 or b2 = true |
||
b1 xor b2 = false |
|||
not b1 = false |
|||
b1 && b2 = true |
|||
short-circuiting operators: |
|||
b1 || b2 = true |
|||
b1 && b2 = true |
|||
b1 || b2 = true |
|||
b1 |
b1 = true |
||
b2 |
b2 = false |
||
non-short-circuiting operators: |
|||
b1 and b2 = false |
|||
b1 |
b1 and b2 = false |
||
b1 |
b1 or b2 = true |
||
b1 xor b2 = true |
|||
b1 |
not b1 = false |
||
short-circuiting operators: |
|||
b1 || b2 = true |
|||
b1 && b2 = false |
|||
b1 || b2 = true |
|||
b1 |
b1 = false |
||
b2 |
b2 = true |
||
non-short-circuiting operators: |
|||
b1 and b2 = false |
|||
b1 |
b1 and b2 = false |
||
b1 |
b1 or b2 = true |
||
b1 xor b2 = true |
|||
not b1 = true |
|||
b1 && b2 = false |
|||
short-circuiting operators: |
|||
b1 || b2 = false |
|||
b1 && b2 = false |
|||
b1 || b2 = true |
|||
b1 |
b1 = false |
||
b2 |
b2 = false |
||
non-short-circuiting operators: |
|||
b1 and b2 = false |
|||
b1 |
b1 and b2 = false |
||
b1 |
b1 or b2 = false |
||
b1 xor b2 = false |
|||
not b1 = true |
|||
b1 && b2 = false |
|||
short-circuiting operators: |
|||
b1 || b2 = true |
|||
b1 && b2 = false |
|||
b1 || b2 = false |
|||
</pre> |
</pre> |
||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{and true true true false true} -> false |
{and true true true false true} -> false |
||
{or true true true false true} -> true |
{or true true true false true} -> true |
||
{not true} -> false |
{not true} -> false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|langur}}== |
=={{header|langur}}== |
||
The logical operators in langur compare the "truthiness" of the left and right operands and do not require Booleans |
The logical operators in langur compare the "truthiness" of the left and right operands and do not require Booleans. |
||
The operators and, or, nand, nor, and?, or?, nand?, nor?, xor?, and nxor? are short-circuiting. |
The operators and, or, nand, nor, and?, or?, nand?, nor?, xor?, and nxor? are short-circuiting. |
||
Line 2,049: | Line 2,250: | ||
Operators that end with ? are null propagating or "database" operators, and will return null if either operand is null. They short-circuit differently than normal operators (only if the left operand is null). |
Operators that end with ? are null propagating or "database" operators, and will return null if either operand is null. They short-circuit differently than normal operators (only if the left operand is null). |
||
<syntaxhighlight lang="langur"> |
|||
<lang langur>val .test = f(.a, .b) join("\n", [ |
|||
val test = fn(a, b) { |
|||
$"not \.a;: \{not .a}", |
|||
join("\n", [ |
|||
$"\.a; and \.b;: \.a and .b;", |
|||
"not {{a}}: {{not a}}", |
|||
"{{a}} and {{b}}: {{a and b}}", |
|||
"{{a}} nand {{b}}: {{a nand b}}", |
|||
"{{a}} or {{b}}: {{a or b}}", |
|||
"{{a}} nor {{b}}: {{a nor b}}", |
|||
"{{a}} xor {{b}}: {{a xor b}}", |
|||
"", |
|||
"{{a}} nxor {{b}}: {{a nxor b}}", |
|||
"", |
|||
$"\.a; and? \.b;: \.a and? .b;", |
|||
"not? {{a}}: {{not? a}}", |
|||
"{{a}} and? {{b}}: {{a and? b}}", |
|||
"{{a}} nand? {{b}}: {{a nand? b}}", |
|||
"{{a}} or? {{b}}: {{a or? b}}", |
|||
"{{a}} nor? {{b}}: {{a nor? b}}", |
|||
"{{a}} xor? {{b}}: {{a xor? b}}", |
|||
"\n", |
|||
"{{a}} nxor? {{b}}: {{a nxor? b}}", |
|||
]) |
|||
"\n", |
|||
]) |
|||
} |
|||
val |
val tests = [ |
||
[true, false], |
[true, false], |
||
[false, true], |
[false, true], |
||
Line 2,083: | Line 2,287: | ||
] |
] |
||
for |
for t in tests { |
||
write |
write test(t[1], t[2]) |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
Line 2,234: | Line 2,439: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">// br is just for formatting output here |
||
define br => '\r' |
define br => '\r' |
||
Line 2,248: | Line 2,453: | ||
'NOT a: ' + !#a |
'NOT a: ' + !#a |
||
br |
br |
||
'NOT a (using not): ' + not #a</ |
'NOT a (using not): ' + not #a</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Line 2,254: | Line 2,459: | ||
0 = false, nonzero = true. |
0 = false, nonzero = true. |
||
A true value is ANY value not zero, but is usually considered to be either "1" or "-1". |
A true value is ANY value not zero, but is usually considered to be either "1" or "-1". |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
False =0 |
False =0 |
||
True =not( False) |
True =not( False) |
||
Line 2,268: | Line 2,473: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
True =-1 False =0 NB True here shown as -1 |
True =-1 False =0 NB True here shown as -1 |
||
. |
. |
||
Line 2,278: | Line 2,483: | ||
=={{header|LIL}}== |
=={{header|LIL}}== |
||
< |
<syntaxhighlight lang="tcl"># Logical operations, in LIL |
||
set first [expr 1 == 1] |
set first [expr 1 == 1] |
||
set second [expr 1 == 0] |
set second [expr 1 == 0] |
||
Line 2,289: | Line 2,494: | ||
} |
} |
||
and-or-not $first $second</ |
and-or-not $first $second</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,299: | Line 2,504: | ||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">function boolOps p1, p2 |
||
local boolOpsResult |
local boolOpsResult |
||
put p1 && "AND" && p2 && "=" && merge("[[p1 and p2]]") & cr after boolOpsResult |
put p1 && "AND" && p2 && "=" && merge("[[p1 and p2]]") & cr after boolOpsResult |
||
Line 2,305: | Line 2,510: | ||
put "NOT" && p1 && "=" && merge("[[not p1]]") & cr after boolOpsResult |
put "NOT" && p1 && "=" && merge("[[not p1]]") & cr after boolOpsResult |
||
return boolOpsResult |
return boolOpsResult |
||
end boolOps</ |
end boolOps</syntaxhighlight> |
||
Example |
Example |
||
< |
<syntaxhighlight lang="livecode">repeat for each item bop in "true,false" |
||
put boolops(bop, bop) & cr after bopResult |
put boolops(bop, bop) & cr after bopResult |
||
put boolops(bop, not bop) & cr after bopResult |
put boolops(bop, not bop) & cr after bopResult |
||
Line 2,328: | Line 2,533: | ||
false AND true = false |
false AND true = false |
||
false OR true = true |
false OR true = true |
||
NOT false = true</ |
NOT false = true</syntaxhighlight> |
||
=={{header|LLVM}}== |
=={{header|LLVM}}== |
||
< |
<syntaxhighlight lang="llvm">; This is not strictly LLVM, as it uses the C library function "printf". |
||
; LLVM does not provide a way to print values, so the alternative would be |
; LLVM does not provide a way to print values, so the alternative would be |
||
; to just load the string into memory, and that would be boring. |
; to just load the string into memory, and that would be boring. |
||
Line 2,431: | Line 2,636: | ||
} |
} |
||
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</ |
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a and b is 0 |
<pre>a and b is 0 |
||
Line 2,448: | Line 2,653: | ||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
The boolean literals are used as words ("true and "false) when used in a program. |
The boolean literals are used as words ("true and "false) when used in a program. |
||
< |
<syntaxhighlight lang="logo">to logic :a :b |
||
(print [a AND b =] and :a :b) |
(print [a AND b =] and :a :b) |
||
(print [a OR b =] or :a :b) |
(print [a OR b =] or :a :b) |
||
(print [NOT a =] not :a) |
(print [NOT a =] not :a) |
||
end</ |
end</syntaxhighlight> |
||
AND and OR may have arity greater than two if used in parentheses (and :a :b :c). |
AND and OR may have arity greater than two if used in parentheses (and :a :b :c). |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
function logic(a,b) |
function logic(a,b) |
||
return a and b, a or b, not a |
return a and b, a or b, not a |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckIt { |
Module CheckIt { |
||
Def Boolean A, B |
Def Boolean A, B |
||
Line 2,497: | Line 2,702: | ||
} |
} |
||
CheckIt |
CheckIt |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,517: | Line 2,722: | ||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`logical', |
||
`and($1,$2)=eval($1&&$2) or($1,$2)=eval($1||$2) not($1)=eval(!$1)') |
`and($1,$2)=eval($1&&$2) or($1,$2)=eval($1||$2) not($1)=eval(!$1)') |
||
logical(1,0)</ |
logical(1,0)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,528: | Line 2,733: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Infix and prefix operators are provided for each of <code>and</code>, <code>or</code>, <code>not</code> as well as <code>xor</code> and <code>implies</code>. |
Infix and prefix operators are provided for each of <code>and</code>, <code>or</code>, <code>not</code> as well as <code>xor</code> and <code>implies</code>. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
f:=proc(a,b) a and b, a or b, not a; end proc: |
f:=proc(a,b) a and b, a or b, not a; end proc: |
||
Line 2,535: | Line 2,740: | ||
f(false,true); |
f(false,true); |
||
f(false,false); |
f(false,false); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> true, true, false |
<pre> true, true, false |
||
Line 2,543: | Line 2,748: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">And[a,b,...] |
||
Or[a,b,...] |
Or[a,b,...] |
||
Not[a]</ |
Not[a]</syntaxhighlight> |
||
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. |
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: |
Furthermore Mathematica supports: |
||
< |
<syntaxhighlight lang="mathematica">Xor[a, b,...] |
||
Nand[a, b,...] |
Nand[a, b,...] |
||
Nor[a, b,...] |
Nor[a, b,...] |
||
Xnor[a, b,...]</ |
Xnor[a, b,...]</syntaxhighlight> |
||
Note that the functions are not restricted to 2 arguments; any number of arguments are allowed (except for the function Not). |
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]. |
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]. |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">f(a, b) := [not a, a or b, a and b]; |
||
/* to use multiple arguments, use any of these */ |
/* to use multiple arguments, use any of these */ |
||
Line 2,564: | Line 2,769: | ||
"or"(a, b, c, d); |
"or"(a, b, c, d); |
||
apply("and", [a, b, c, d]); |
apply("and", [a, b, c, d]); |
||
apply("or", [a, b, c, d]);</ |
apply("or", [a, b, c, d]);</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn printLogic a b = |
||
( |
( |
||
format "a and b is %\n" (a and b) |
format "a and b is %\n" (a and b) |
||
format "a or b is %\n" (a or b) |
format "a or b is %\n" (a or b) |
||
format "not a is %\n" (not a) |
format "not a is %\n" (not a) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
< |
<syntaxhighlight lang="metafont">def tf(expr a) = if a: "true" else: "false" fi enddef; |
||
def test(expr a, b) = |
def test(expr a, b) = |
||
for o = "and", "or": |
for o = "and", "or": |
||
Line 2,583: | Line 2,788: | ||
endfor |
endfor |
||
message "not " & tf(a); |
message "not " & tf(a); |
||
show not a enddef;</ |
show not a enddef;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="metafont">test(true, true); |
||
test(false, false); |
test(false, false); |
||
test(true, false); |
test(true, false); |
||
test(false, true); |
test(false, true); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang="min">( |
||
:b :a |
:b :a |
||
"xor is: " print! a b xor puts! |
"xor is: " print! a b xor puts! |
||
Line 2,599: | Line 2,804: | ||
"or is: " print! a b or puts! |
"or is: " print! a b or puts! |
||
"not is: " print! a not puts! |
"not is: " print! a not puts! |
||
) :logical-operators</ |
) :logical-operators</syntaxhighlight> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE LogicalOps; |
||
FROM FormatString IMPORT FormatString; |
FROM FormatString IMPORT FormatString; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 2,625: | Line 2,830: | ||
ReadChar |
ReadChar |
||
END LogicalOps.</ |
END LogicalOps.</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Logical EXPORTS Main; |
||
FROM IO IMPORT Put; |
FROM IO IMPORT Put; |
||
Line 2,642: | Line 2,847: | ||
BEGIN |
BEGIN |
||
Test(TRUE, FALSE); |
Test(TRUE, FALSE); |
||
END Logical.</ |
END Logical.</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
<syntaxhighlight lang="mumps"> |
|||
<lang MUMPS> |
|||
LOGIC(A,B) |
LOGIC(A,B) |
||
WRITE !,A," AND ",B," IS ",A&B |
WRITE !,A," AND ",B," IS ",A&B |
||
Line 2,651: | Line 2,856: | ||
WRITE !,"NOT ",A," AND ",B," IS ",'(A)&B |
WRITE !,"NOT ",A," AND ",B," IS ",'(A)&B |
||
WRITE !,"NOT ",A," OR ",B," IS ",'(A)!B |
WRITE !,"NOT ",A," OR ",B," IS ",'(A)!B |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nanoquery">def logic(a, b) |
||
println "a and b: " + (a && b) |
println "a and b: " + (a && b) |
||
println "a or b: " + (a && b) |
println "a or b: " + (a && b) |
||
println "not a: " + !a |
println "not a: " + !a |
||
end</ |
end</syntaxhighlight> |
||
While this is translated from Python, Nanoquery does not allow any object to be treated as a boolean value. As a result, this function must be called with explicit boolean values. |
While this is translated from Python, Nanoquery does not allow any object to be treated as a boolean value. As a result, this function must be called with explicit boolean values. |
||
{{out}} |
{{out}} |
||
Line 2,673: | Line 2,878: | ||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
<syntaxhighlight lang="actionscript">/** |
|||
<lang ActionScript>/** |
|||
Logical operations, in Neko |
Logical operations, in Neko |
||
*/ |
*/ |
||
Line 2,688: | Line 2,893: | ||
if $istrue(logical) && logical > 0 $print("true path for logical AND\n") |
if $istrue(logical) && logical > 0 $print("true path for logical AND\n") |
||
if $istrue(logical) || logical > 1 $print("true path for logical OR\n") |
if $istrue(logical) || logical > 1 $print("true path for logical OR\n") |
||
if $not(logical) $print("true path for $not(1)\n") else $print("false path for $not(1)\n")</ |
if $not(logical) $print("true path for $not(1)\n") else $print("false path for $not(1)\n")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,700: | Line 2,905: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 2,713: | Line 2,918: | ||
Main() : void {WriteLogical(true, false)} |
Main() : void {WriteLogical(true, false)} |
||
}</ |
}</syntaxhighlight> |
||
Or, if you prefer keywords to operators import the Nemerle.English namespace to use '''and''', '''or''', and '''not'''. |
Or, if you prefer keywords to operators import the Nemerle.English namespace to use '''and''', '''or''', and '''not'''. |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols binary |
options replace format comments java crossref symbols binary |
||
Line 2,754: | Line 2,959: | ||
end lx |
end lx |
||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,779: | Line 2,984: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp"> |
||
(define (logic a b) |
(define (logic a b) |
||
(print "a and b is: " (and a b) "\n a or b is: " (or 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))) |
(print "\n not a is: " (not a))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc logic(a, b: bool) = |
||
echo "a and b: ", a and b |
echo "a and b: ", a and b |
||
echo "a or b: ", a or b |
echo "a or b: ", a or b |
||
echo "not a: ", not a |
echo "not a: ", not a |
||
echo "a xor b: ", a xor b</ |
echo "a xor b: ", a xor b</syntaxhighlight> |
||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
def ops [a b] {{A: $a, B: $b, "Not A": (not $a), OR: ($a or $b), AND: ($a and $b), XOR: ($a xor $b)}} |
|||
[true false] | each {[[true $in] [false $in]]} | flatten | each {ops $in.0 $in.1} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
╭───┬───────┬───────┬───────┬───────┬───────┬───────╮ |
|||
│ # │ A │ B │ Not A │ OR │ AND │ XOR │ |
|||
├───┼───────┼───────┼───────┼───────┼───────┼───────┤ |
|||
│ 0 │ true │ true │ false │ true │ true │ false │ |
|||
│ 1 │ false │ true │ true │ true │ false │ true │ |
|||
│ 2 │ true │ false │ false │ true │ false │ true │ |
|||
│ 3 │ false │ false │ true │ false │ false │ false │ |
|||
╰───┴───────┴───────┴───────┴───────┴───────┴───────╯ |
|||
</pre> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Logic { |
class Logic { |
||
Line 2,806: | Line 3,029: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let print_logic a b = |
||
Printf.printf "a and b is %B\n" (a && b); |
Printf.printf "a and b is %B\n" (a && b); |
||
Printf.printf "a or 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)</ |
Printf.printf "not a is %B\n" (not a)</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function test(a, b) |
||
s1 = num2str(a); |
s1 = num2str(a); |
||
s2 = num2str(b); |
s2 = num2str(b); |
||
Line 2,829: | Line 3,052: | ||
test(false, false); |
test(false, false); |
||
test(true, false); |
test(true, false); |
||
test(false, true);</ |
test(false, true);</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: logical(b1, b2) |
||
System.Out "and = " << b1 b2 and << cr |
System.Out "and = " << b1 b2 and << cr |
||
System.Out "or = " << b1 b2 or << cr |
System.Out "or = " << b1 b2 or << cr |
||
System.Out "xor = " << b1 b2 xor << cr |
System.Out "xor = " << b1 b2 xor << cr |
||
System.Out "not = " << b1 not << cr ;</ |
System.Out "not = " << b1 not << cr ;</syntaxhighlight> |
||
=={{header|OOC}}== |
=={{header|OOC}}== |
||
Bools in ooc are just covers for C's bools and respond to the same operators. |
Bools in ooc are just covers for C's bools and respond to the same operators. |
||
< |
<syntaxhighlight lang="ooc"> |
||
logic: func (a: Bool, b: Bool) { |
logic: func (a: Bool, b: Bool) { |
||
println() |
println() |
||
Line 2,856: | Line 3,079: | ||
logic(false, true) |
logic(false, true) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
The logical data type can have three values: true, false or unknown (represented by question mark). |
The logical data type can have three values: true, false or unknown (represented by question mark). |
||
< |
<syntaxhighlight lang="progress">FUNCTION testLogical RETURNS CHAR ( |
||
i_l1 AS LOGICAL, |
i_l1 AS LOGICAL, |
||
i_l2 AS LOGICAL |
i_l2 AS LOGICAL |
||
Line 2,872: | Line 3,095: | ||
. |
. |
||
END FUNCTION.</ |
END FUNCTION.</syntaxhighlight> |
||
< |
<syntaxhighlight lang="progress">MESSAGE |
||
testLogical( FALSE, FALSE ) SKIP(1) |
testLogical( FALSE, FALSE ) SKIP(1) |
||
testLogical( FALSE, TRUE ) SKIP(1) |
testLogical( FALSE, TRUE ) SKIP(1) |
||
Line 2,882: | Line 3,105: | ||
testLogical( ?, FALSE ) SKIP(1) |
testLogical( ?, FALSE ) SKIP(1) |
||
testLogical( ?, TRUE ) SKIP(1) |
testLogical( ?, TRUE ) SKIP(1) |
||
VIEW-AS ALERT-BOX.</ |
VIEW-AS ALERT-BOX.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,922: | Line 3,145: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">proc {PrintLogic A B} |
||
%% using not short-circuiting standard library functions |
%% using not short-circuiting standard library functions |
||
{Show {And A B}} |
{Show {And A B}} |
||
Line 2,931: | Line 3,154: | ||
{Show A andthen B} |
{Show A andthen B} |
||
{Show A orelse B} |
{Show A orelse B} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Note that the forms <code>bitand()</code>, <code>bitor()</code>, <code>bitneg()</code>, and <code>bitxor()</code> also exist. These apply the operator to each bit and do not short-circuit, unlike the below. |
Note that the forms <code>bitand()</code>, <code>bitor()</code>, <code>bitneg()</code>, and <code>bitxor()</code> also exist. These apply the operator to each bit and do not short-circuit, unlike the below. |
||
< |
<syntaxhighlight lang="parigp">logic(a,b)={ |
||
print(a&b); \\ && is the same |
print(a&b); \\ && is the same |
||
print(a|b); \\ || is the same |
print(a|b); \\ || is the same |
||
print(!a); |
print(!a); |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Nine logical operators are standard. |
|||
<lang pascal>procedure printlogic(a, b: boolean); |
|||
Since [[Boolean values#Pascal|<tt>Boolean</tt> is a built-in enumeration data type]], all relational operators except the membership operator (<tt>in</tt>) are applicable. |
|||
begin |
|||
Moreover, [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]] support the exclusive operator <tt>xor</tt>. |
|||
writeln('a and b is ', a and b); |
|||
<syntaxhighlight lang="pascal">function logicalOperations(A, B: Boolean): Boolean; |
|||
writeln('a or b is ', a or b); |
|||
begin |
|||
writeln('not a is', not a); |
|||
{ logical conjunction } |
|||
end;</lang> |
|||
writeLn(A:5, ' and', B:6, ' yields', A and B:7); |
|||
{ logical disjunction } |
|||
writeLn(A:5, ' or', B:6, ' yields', A or B:7); |
|||
{ logical negation } |
|||
writeLn(' not', A:6, ' yields', not A:7); |
|||
{ logical equivalence } |
|||
writeLn(A:5, ' =', B:6, ' yields', A = B:7); |
|||
{ negation of logical equivalence } |
|||
writeLn(A:5, ' <>', B:6, ' yields', A <> B:7); |
|||
{ relational operators } |
|||
writeLn(A:5, ' <', B:6, ' yields', A < B:7); |
|||
writeLn(A:5, ' >', B:6, ' yields', A > B:7); |
|||
writeLn(A:5, ' <=', B:6, ' yields', A <= B:7); |
|||
writeLn(A:5, ' >=', B:6, ' yields', A >= B:7); |
|||
{ fulfill task requirement of writing a function: } |
|||
logicalOperations := true |
|||
end;</syntaxhighlight> |
|||
Furthermore, [[Extended Pascal]] (ISO standard 10206) defines two additional logical operators. |
|||
The operators <tt>and_then</tt> and <tt>or_else</tt> are intended for [[Short-circuit evaluation#Pascal|short-circuit evaluation]]. |
|||
However, since all actual parameters need to be evaluated ''prior'' activation of the function, it makes little sense to use/show them in the above sample code. |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub show_bool |
||
{ |
{ |
||
return shift() ? 'true' : 'false', "\n"; |
return shift() ? 'true' : 'false', "\n"; |
||
Line 2,963: | Line 3,206: | ||
print "not a is ", show_bool !$a; |
print "not a is ", show_bool !$a; |
||
print "a xor b is ", show_bool($a xor $b); |
print "a xor b is ", show_bool($a xor $b); |
||
}</ |
}</syntaxhighlight> |
||
There are also <code>and</code>, <code>or</code>, and <code>not</code> operators. These are just like <code>&&</code>, <code>||</code>, and <code>!</code> (respectively) except for their precedences, which are much lower. |
There are also <code>and</code>, <code>or</code>, and <code>not</code> operators. These are just like <code>&&</code>, <code>||</code>, and <code>!</code> (respectively) except for their precedences, which are much lower. |
||
=={{header|PascalABC.NET}}== |
|||
''See [[#Delphi|Delphi]] |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 2,974: | Line 3,220: | ||
Other relational operators and maths are also valid, if you wanna get clever. |
Other relational operators and maths are also valid, if you wanna get clever. |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">logicop</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">logicop</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">and</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">or</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #008080;">not</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">xor</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">==</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> |
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">and</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">or</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #008080;">not</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">xor</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">==</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> |
||
Line 2,985: | Line 3,231: | ||
<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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
Line 2,997: | Line 3,243: | ||
Simpler version using plain integer flags: |
Simpler version using plain integer flags: |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">logiicop</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">logiicop</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">and</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">or</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #008080;">not</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">xor</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> |
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">and</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">or</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #008080;">not</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span> <span style="color: #008080;">xor</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> |
||
Line 3,008: | Line 3,254: | ||
<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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
Line 3,018: | Line 3,264: | ||
1 1 1 1 0 0 1 0 |
1 1 1 1 0 0 1 0 |
||
</pre> |
</pre> |
||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/Logical_operations |
|||
by Galileo, 11/2022 #/ |
|||
include ..\Utilitys.pmt |
|||
def logiicop var b var a |
|||
( a b a b and a b or a not a b xor a b == a b != ) |
|||
enddef |
|||
def printSec |
|||
len for get print "\t" print endfor drop nl |
|||
enddef |
|||
( "a" "b" "and" "or" "not" "xor" "==" "!=" ) printSec |
|||
( 0 1 ) for dup |
|||
( 0 1 ) for |
|||
logiicop printSec |
|||
endfor |
|||
endfor</syntaxhighlight> |
|||
{{out}} |
|||
<pre>a b and or not xor == != |
|||
0 0 0 0 1 0 1 0 |
|||
0 1 0 1 1 1 0 1 |
|||
1 0 0 1 0 1 0 1 |
|||
1 1 1 1 0 0 1 0 |
|||
=== Press any key to exit ===</pre> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function print_logic($a, $b) |
||
{ |
{ |
||
echo "a and b is ", $a && $b ? 'True' : 'False', "\n"; |
echo "a and b is ", $a && $b ? 'True' : 'False', "\n"; |
||
echo "a or 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"; |
echo "not a is ", ! $a ? 'True' : 'False', "\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de logic (A B) |
||
(prin "A AND B is ") |
(prin "A AND B is ") |
||
(println (and A B)) |
(println (and A B)) |
||
Line 3,037: | Line 3,312: | ||
(println (xor A B)) |
(println (xor A B)) |
||
(prin "NOT A is ") |
(prin "NOT A is ") |
||
(println (not A)) )</ |
(println (not A)) )</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">logical_ops: procedure (t, u); |
||
declare (t, u) bit (1); |
declare (t, u) bit (1); |
||
Line 3,047: | Line 3,322: | ||
put skip list (^t); /* logical not */ |
put skip list (^t); /* logical not */ |
||
put skip list (t ^ u); /* exclusive or */ |
put skip list (t ^ u); /* exclusive or */ |
||
end logical_ops;</ |
end logical_ops;</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">define print_logic(a, b); |
||
printf(a and b, 'a and b is %p\n'); |
printf(a and b, 'a and b is %p\n'); |
||
printf(a or b, 'a or b is %p\n'); |
printf(a or b, 'a or b is %p\n'); |
||
printf(not(a), 'not a is %p\n'); |
printf(not(a), 'not a is %p\n'); |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
Example usage is: |
Example usage is: |
||
<lang |
<syntaxhighlight lang="pop11">print_logic(true, false);</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang="postscript"> |
||
/logical{ |
/logical{ |
||
/a exch def |
/a exch def |
||
Line 3,069: | Line 3,344: | ||
a not = |
a not = |
||
}def |
}def |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">function Test-Boolean ([bool] $a, [bool] $b) { |
||
Write-Host "A and B: " ($a -and $b) |
Write-Host "A and B: " ($a -and $b) |
||
Write-Host "A or B: " ($a -or $b) |
Write-Host "A or B: " ($a -or $b) |
||
Line 3,078: | Line 3,353: | ||
Write-Host "not A: " (!$a) |
Write-Host "not A: " (!$a) |
||
Write-Host "A xor B: " ($a -xor $b) |
Write-Host "A xor B: " ($a -xor $b) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 3,115: | Line 3,390: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure LogicDebug(a,b) |
||
Debug a & b ;And |
Debug a & b ;And |
||
Debug a | b ;Or |
Debug a | b ;Or |
||
Line 3,124: | Line 3,399: | ||
logicDebug(#True, #True) |
logicDebug(#True, #True) |
||
logicDebug(#True, #False) |
logicDebug(#True, #False) |
||
logicDebug(#False, #False)</ |
logicDebug(#False, #False)</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def logic(a, b): |
||
print('a and b:', a and b) |
print('a and b:', a and b) |
||
print('a or b:', a or b) |
print('a or b:', a or b) |
||
print('not a:', not a)</ |
print('not a:', not a)</syntaxhighlight> |
||
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. |
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. |
||
Line 3,136: | Line 3,411: | ||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
<syntaxhighlight lang="qb64"> |
|||
<lang QB64> |
|||
Dim As _Unsigned _Bit First, Second |
Dim As _Unsigned _Bit First, Second |
||
First = 0: Second = 1 |
First = 0: Second = 1 |
||
Line 3,149: | Line 3,424: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 3,155: | Line 3,430: | ||
Quackery also has the boolean words <code>nand</code> and <code>xor</code>. |
Quackery also has the boolean words <code>nand</code> and <code>xor</code>. |
||
< |
<syntaxhighlight lang="quackery"> [ iff [ say "true" ] |
||
else [ say "false"] ] is echobool ( b --> ) |
else [ say "false"] ] is echobool ( b --> ) |
||
Line 3,163: | Line 3,438: | ||
say "A or B is " echobool cr |
say "A or B is " echobool cr |
||
not |
not |
||
say "not A is " echobool cr ] is task ( A B --> )</ |
say "not A is " echobool cr ] is task ( A B --> )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,202: | Line 3,477: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">logic <- function(a, b) { |
||
print(a && b) |
print(a && b) |
||
print(a || b) |
print(a || b) |
||
Line 3,210: | Line 3,485: | ||
logic(TRUE, TRUE) |
logic(TRUE, TRUE) |
||
logic(TRUE, FALSE) |
logic(TRUE, FALSE) |
||
logic(FALSE, FALSE)</ |
logic(FALSE, FALSE)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (logic a b) |
(define (logic a b) |
||
Line 3,222: | Line 3,497: | ||
(displayln (format "a nor b equals ~a" (nor a b))) |
(displayln (format "a nor b equals ~a" (nor a b))) |
||
(displayln (format "a implies b equals ~a" (implies a b))) |
(displayln (format "a implies b equals ~a" (implies a b))) |
||
(displayln (format "a xor b equals ~a" (xor a b))))</ |
(displayln (format "a xor b equals ~a" (xor a b))))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 3,228: | Line 3,503: | ||
Raku has an abundance of logical operators for various purposes. |
Raku has an abundance of logical operators for various purposes. |
||
<lang |
<syntaxhighlight lang="raku" line>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; # short-circuiting |
say "$a || $b is ", $a || $b; # short-circuiting |
||
Line 3,256: | Line 3,531: | ||
} |
} |
||
logic(3,10);</ |
logic(3,10);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>3 && 10 is 10 |
<pre>3 && 10 is 10 |
||
Line 3,280: | Line 3,555: | ||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">import IO; |
||
public void logic(bool a, bool b){ |
public void logic(bool a, bool b){ |
||
Line 3,288: | Line 3,563: | ||
println("a implies b, is <a ==> b>"); |
println("a implies b, is <a ==> b>"); |
||
println("not a", <!a>"); |
println("not a", <!a>"); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,301: | Line 3,576: | ||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">logics: func [a [logic!] b [logic!]] [ |
||
print ['and tab a and b] |
print ['and tab a and b] |
||
print ['or tab a or b] |
print ['or tab a or b] |
||
Line 3,313: | Line 3,588: | ||
print ['any tab any [a b]] |
print ['any tab any [a b]] |
||
print ['all tab all [a b]] |
print ['all tab all [a b]] |
||
]</ |
]</syntaxhighlight> |
||
Example: |
Example: |
||
Line 3,330: | Line 3,605: | ||
=={{header|Relation}}== |
=={{header|Relation}}== |
||
<syntaxhighlight lang="relation"> |
|||
<lang Relation> |
|||
program logic(x,y) |
program logic(x,y) |
||
relation a, b, op, result |
relation a, b, op, result |
||
Line 3,344: | Line 3,619: | ||
run logic(1,0) |
run logic(1,0) |
||
run logic(1,1) |
run logic(1,1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
In Relation TRUE is the number 1 (or any different from 0) and FALSE 0. |
In Relation TRUE is the number 1 (or any different from 0) and FALSE 0. |
||
=={{header|ReScript}}== |
=={{header|ReScript}}== |
||
< |
<syntaxhighlight lang="rescript">let logic = (a, b) => { |
||
Js.log(string_of_bool(a) ++ " and " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a && b)) |
Js.log(string_of_bool(a) ++ " and " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a && b)) |
||
Js.log(string_of_bool(a) ++ " or " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a || b)) |
Js.log(string_of_bool(a) ++ " or " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a || b)) |
||
Line 3,362: | Line 3,637: | ||
logic2(true) |
logic2(true) |
||
logic2(false)</ |
logic2(false)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,380: | Line 3,655: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">: .bool ( f- ) [ "true" ] [ "false" ] if puts cr ; |
||
: logic ( ab- ) |
: logic ( ab- ) |
||
"\na = " puts over .bool "b = " puts dup .bool |
"\na = " puts over .bool "b = " puts dup .bool |
||
"\na and b = " puts 2dup and .bool |
"\na and b = " puts 2dup and .bool |
||
"\na or b = " puts over or .bool |
"\na or b = " puts over or .bool |
||
"\nnot a = " puts not .bool ;</ |
"\nnot a = " puts not .bool ;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 3,396: | Line 3,671: | ||
Any other value will raise a REXX '''syntax''' error condition. |
Any other value will raise a REXX '''syntax''' error condition. |
||
===basic boolean functions=== |
===basic boolean functions=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates some binary (also known as bit or logical) operations.*/ |
||
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */ |
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */ |
||
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */ |
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */ |
||
Line 3,421: | Line 3,696: | ||
@.= copies('═', 7) /*define a new header separator line. */ |
@.= copies('═', 7) /*define a new header separator line. */ |
||
end /*j*/ |
end /*j*/ |
||
return</ |
return</syntaxhighlight> |
||
{{out|output|text= when using the default (internal) inputs:}} |
{{out|output|text= when using the default (internal) inputs:}} |
||
<pre> |
<pre> |
||
Line 3,460: | Line 3,735: | ||
===extended boolean functions=== |
===extended boolean functions=== |
||
All sixteen boolean functions could easily be shown. |
All sixteen boolean functions could easily be shown. |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm demonstrates some binary (also known as bit or logical) extended operations.*/ |
||
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */ |
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */ |
||
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */ |
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */ |
||
Line 3,490: | Line 3,765: | ||
@.= copies('═', 7) /*define a new separator (header) line.*/ |
@.= copies('═', 7) /*define a new separator (header) line.*/ |
||
end /*j*/ |
end /*j*/ |
||
return</ |
return</syntaxhighlight> |
||
{{out|output|text= when using the default (internal) inputs:}} |
{{out|output|text= when using the default (internal) inputs:}} |
||
<pre> |
<pre> |
||
Line 3,549: | Line 3,824: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
x = true |
x = true |
||
y = false |
y = false |
||
Line 3,556: | Line 3,831: | ||
see "x or y = " + (x or y) + nl |
see "x or y = " + (x or y) + nl |
||
see "not x = " + (not x) + nl |
see "not x = " + (not x) + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 3,562: | Line 3,837: | ||
<code>and/or/not</code> are synonymous with <code>&&/||/!</code>. In the case when the argument is a real number (default type of argument) the default statement in the absence of ''if'' command is ''is the argument non-zero''. |
<code>and/or/not</code> are synonymous with <code>&&/||/!</code>. In the case when the argument is a real number (default type of argument) the default statement in the absence of ''if'' command is ''is the argument non-zero''. |
||
Therefore |
Therefore |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> x = 5 |
>> x = 5 |
||
5 |
5 |
||
Line 3,573: | Line 3,848: | ||
>> x && y |
>> x && y |
||
0 |
0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
However, if arguments to the functions are of the type ''integer'' then the functions operate bit-wise. |
However, if arguments to the functions are of the type ''integer'' then the functions operate bit-wise. |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> x = int(5) |
>> x = int(5) |
||
5 |
5 |
||
Line 3,587: | Line 3,862: | ||
>> x && y |
>> x && y |
||
0 |
0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Robotic}}== |
=={{header|Robotic}}== |
||
Line 3,593: | Line 3,868: | ||
However, [[Bitwise_operations|bitwise operators]] can be used. |
However, [[Bitwise_operations|bitwise operators]] can be used. |
||
=={{header|RPL}}== |
|||
≪ → a b |
|||
≪ "a and b = " a b AND →STR + |
|||
"a or b = " a b OR →STR + |
|||
"not a = " a NOT →STR + |
|||
"a xor b = " a b XOR →STR + |
|||
≫ ≫ ''''LOGIC'''' STO |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def logic(a, b) |
||
print 'a and b: ', a && b, "\n" |
print 'a and b: ', a && b, "\n" |
||
print 'a or b: ' , a || b, "\n" |
print 'a or b: ' , a || b, "\n" |
||
print 'not a: ' , !a , "\n" |
print 'not a: ' , !a , "\n" |
||
print 'a xor b: ' , a ^ b, "\n" |
print 'a xor b: ' , a ^ b, "\n" |
||
end</ |
end</syntaxhighlight> |
||
<code>and/or/not</code> are synonymous with <code>&&/||/!</code> albeit with lower precedence. |
<code>and/or/not</code> are synonymous with <code>&&/||/!</code> albeit with lower precedence. |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{works with|Rust|1.1}} |
{{works with|Rust|1.1}} |
||
<syntaxhighlight lang="rust"> |
|||
<lang Rust> |
|||
fn boolean_ops(a: bool, b: bool) { |
fn boolean_ops(a: bool, b: bool) { |
||
println!("{} and {} -> {}", a, b, a && b); |
println!("{} and {} -> {}", a, b, a && b); |
||
Line 3,618: | Line 3,900: | ||
boolean_ops(false, false) |
boolean_ops(false, false) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
The Boolean operators || and && are more efficient versions of | and & in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression. |
The Boolean operators || and && are more efficient versions of | and & in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression. |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
In vanilla Scala: |
In vanilla Scala: |
||
< |
<syntaxhighlight lang="scala">def logical(a: Boolean, b: Boolean): Unit = { |
||
println("and: " + (a && b)) |
println("and: " + (a && b)) |
||
println("or: " + (a || b)) |
println("or: " + (a || b)) |
||
Line 3,629: | Line 3,911: | ||
} |
} |
||
logical(true, false)</ |
logical(true, false)</syntaxhighlight> |
||
With Scalaz: |
With Scalaz: |
||
< |
<syntaxhighlight lang="scala">def logical(a: Boolean, b: Boolean): IO[Unit] = for { |
||
_ <- putStrLn("and: " ++ (a && b).shows) |
_ <- putStrLn("and: " ++ (a && b).shows) |
||
_ <- putStrLn("or: " ++ (a || b).shows) |
_ <- putStrLn("or: " ++ (a || b).shows) |
||
Line 3,638: | Line 3,920: | ||
} yield () |
} yield () |
||
logical(true, false).unsafePerformIO</ |
logical(true, false).unsafePerformIO</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (logic a b) |
||
(display "a and b is ") |
(display "a and b is ") |
||
(display (and a b)) |
(display (and a b)) |
||
Line 3,650: | Line 3,932: | ||
(display "not a is ") |
(display "not a is ") |
||
(display (not a)) |
(display (not a)) |
||
(newline))</ |
(newline))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">const proc: writeLogic (in boolean: a, in boolean: b) is func |
||
begin |
begin |
||
writeln("a and b is " <& a and b); |
writeln("a and b is " <& a and b); |
||
writeln("a or b is " <& a or b); |
writeln("a or b is " <& a or b); |
||
writeln("not a is " <& not a); |
writeln("not a is " <& not a); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Self}}== |
=={{header|Self}}== |
||
< |
<syntaxhighlight lang="self">true not = false. |
||
( true && false ) = false. |
( true && false ) = false. |
||
( true ^^ false ) = true. "xor" |
( true ^^ false ) = true. "xor" |
||
( true || false ) = true. "or" |
( true || false ) = true. "or" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func logic(a, b) { |
||
say ("a and b: ", a && b); |
say ("a and b: ", a && b); |
||
say ("a or b: ", a || b); |
say ("a or b: ", a || b); |
||
Line 3,676: | Line 3,958: | ||
} |
} |
||
logic(false, true);</ |
logic(false, true);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a and b: false |
<pre>a and b: false |
||
Line 3,689: | Line 3,971: | ||
This makes a closure that takes two Boolean values. Booleans can be indicated by predicate identifier names that end with a question mark <code>?</code>. |
This makes a closure that takes two Boolean values. Booleans can be indicated by predicate identifier names that end with a question mark <code>?</code>. |
||
< |
<syntaxhighlight lang="javascript">!logic: |
||
(a? b?) |
(a? b?) |
||
[ |
[ |
||
Line 3,700: | Line 3,982: | ||
println("a not xor b: " a nxor b) |
println("a not xor b: " a nxor b) |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example call: |
Example call: |
||
<lang |
<syntaxhighlight lang="javascript">logic(true false)</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
{{lines too long|Slate}} |
{{lines too long|Slate}} |
||
< |
<syntaxhighlight lang="slate">{#/\. #\/. #not} do: [ |:func| |
||
func arity = 1 ifTrue: [inform: 'True ' ; (func as: String) ; ' = ' ; (func sendTo: {True}) printString. |
func arity = 1 ifTrue: [inform: 'True ' ; (func as: String) ; ' = ' ; (func sendTo: {True}) printString. |
||
inform: 'False ' ; (func as: String) ; ' = ' ; (func sendTo: {False}) printString.]. |
inform: 'False ' ; (func as: String) ; ' = ' ; (func sendTo: {False}) printString.]. |
||
Line 3,716: | Line 3,998: | ||
[ |:each| inform: each first printString ; (func as: String) ; each second printString ; ' = ' ; (func sendTo: each) printString]] |
[ |:each| inform: each first printString ; (func as: String) ; each second printString ; ' = ' ; (func sendTo: each) printString]] |
||
].</ |
].</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,737: | Line 4,019: | ||
There are also non-evaluating versions named "and:" and "or:", which only evaluate expr2 if the result is not already determined by expr1. |
There are also non-evaluating versions named "and:" and "or:", which only evaluate expr2 if the result is not already determined by expr1. |
||
< |
<syntaxhighlight lang="smalltalk">|test| |
||
test := [ :a :b | |
test := [ :a :b | |
||
('%1 %2 %3 = %4' % { a. 'and'. b. (a & b) }) displayNl. |
('%1 %2 %3 = %4' % { a. 'and'. b. (a & b) }) displayNl. |
||
Line 3,747: | Line 4,029: | ||
test value: false value: false. |
test value: false value: false. |
||
test value: true value: false. |
test value: true value: false. |
||
test value: false value: true.</ |
test value: false value: true.</syntaxhighlight> |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
< |
<syntaxhighlight lang="smalltalk">a implies: b |
||
a xor: b</ |
a xor: b</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">fun print_logic (a, b) = ( |
||
print ("a and b is " ^ Bool.toString (a andalso b) ^ "\n"); |
print ("a and b is " ^ Bool.toString (a andalso b) ^ "\n"); |
||
print ("a or b is " ^ Bool.toString (a orelse b) ^ "\n"); |
print ("a or b is " ^ Bool.toString (a orelse b) ^ "\n"); |
||
print ("not a is " ^ Bool.toString (not a) ^ "\n") |
print ("not a is " ^ Bool.toString (not a) ^ "\n") |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 3,766: | Line 4,048: | ||
Stata does not have a boolean type, and uses instead 0 and 1 to denote resp. false and true. |
Stata does not have a boolean type, and uses instead 0 and 1 to denote resp. false and true. |
||
< |
<syntaxhighlight lang="stata">prog def bool |
||
args a b |
args a b |
||
di `a'&`b' |
di `a'&`b' |
||
di `a'|`b' |
di `a'|`b' |
||
di !`a' |
di !`a' |
||
end</ |
end</syntaxhighlight> |
||
Likewise in Mata: |
Likewise in Mata: |
||
< |
<syntaxhighlight lang="stata">function bool(a,b) { |
||
printf("%f\n",a&b) |
printf("%f\n",a&b) |
||
printf("%f\n",a|b) |
printf("%f\n",a|b) |
||
printf("%f\n",!a) |
printf("%f\n",!a) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func logic(a: Bool, b: Bool) { |
||
println("a AND b: \(a && b)"); |
println("a AND b: \(a && b)"); |
||
println("a OR b: \(a || b)"); |
println("a OR b: \(a || b)"); |
||
println("NOT a: \(!a)"); |
println("NOT a: \(!a)"); |
||
}</ |
}</syntaxhighlight> |
||
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication). |
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication). |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc logic {a b} { |
||
puts "a and b: [expr {$a && $b}]" |
puts "a and b: [expr {$a && $b}]" |
||
puts "a or b: [expr {$a || $b}]" |
puts "a or b: [expr {$a || $b}]" |
||
puts "not a: [expr {!$a}]" |
puts "not a: [expr {!$a}]" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Terraform}}== |
|||
The Hashicorp Configuration Language ( HCL ) does not support user defined functions. It only supports AND, OR and NOT logical operations. HCL is not meant for generic programming but I don't see an use case for a logarithm function in a language meant to provision infrastructure either. So...... |
|||
<syntaxhighlight lang="terraform"> |
|||
#Aamrun, August 15th 2022 |
|||
variable "a" { |
|||
type = bool |
|||
default = true |
|||
} |
|||
variable "b" { |
|||
type = bool |
|||
default = false |
|||
} |
|||
output "a_and_b" { |
|||
value = var.a && var.b |
|||
} |
|||
output "a_or_b" { |
|||
value = var.a || var.b |
|||
} |
|||
output "not_a" { |
|||
value = !var.a |
|||
} |
|||
</syntaxhighlight> |
|||
'''Invocation and output :''' |
|||
<pre> |
|||
$ terraform apply -var="a=true" -var="b=false" -auto-approve |
|||
No changes. Your infrastructure matches the configuration. |
|||
Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed. |
|||
Apply complete! Resources: 0 added, 0 changed, 0 destroyed. |
|||
Outputs: |
|||
a_and_b = false |
|||
a_or_b = true |
|||
not_a = false |
|||
$ |
|||
</pre> |
|||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
Line 3,802: | Line 4,130: | ||
that are the same as the well-formed flags in Forth. |
that are the same as the well-formed flags in Forth. |
||
< |
<syntaxhighlight lang="toka">[ 0 <> [ ." true" ] [ ." false"] ifTrueFalse ] is .bool |
||
[ ( a b -- ) |
[ ( a b -- ) |
||
cr ." a = " over .bool ." b = " dup .bool |
cr ." a = " over .bool ." b = " dup .bool |
||
Line 3,808: | Line 4,136: | ||
cr ." a or b = " over or .bool |
cr ." a or b = " over or .bool |
||
cr ." not a = " 0 = .bool |
cr ." not a = " 0 = .bool |
||
] is logic</ |
] is logic</syntaxhighlight> |
||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
uBasic/4tH does not have logical operators, but every non-zero value will be considered ''TRUE'' in conditional statements. However, comparison operators (like =, #, < and >) can be used in expressions and will return fully qualified booleans. Hence, simple arithmetic operators will do the trick just fine. |
uBasic/4tH does not have logical operators, but every non-zero value will be considered ''TRUE'' in conditional statements. However, comparison operators (like =, #, < and >) can be used in expressions and will return fully qualified booleans. Hence, simple arithmetic operators will do the trick just fine. |
||
<lang>Proc _Boolean(4, 2) |
<syntaxhighlight lang="text">Proc _Boolean(4, 2) |
||
Proc _Boolean(0, 2) |
Proc _Boolean(0, 2) |
||
Proc _Boolean(2, 0) |
Proc _Boolean(2, 0) |
||
Line 3,827: | Line 4,155: | ||
print "not A is "; a@ = 0 ' This will invert the boolean value |
print "not A is "; a@ = 0 ' This will invert the boolean value |
||
print |
print |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>A and B is 1 |
<pre>A and B is 1 |
||
Line 3,843: | Line 4,171: | ||
0 OK, 0:63</pre> |
0 OK, 0:63</pre> |
||
=={{header|UNIX Shell}}== |
|||
The shell has at least two levels of logical operators. Conditional logic (<tt>if</tt>, <tt>while</tt>, <tt>&&</tt> and <tt>||</tt> at the statement level) operates on commands; the commands are executed, and their exit status determines their value in a Boolean context. If they return an exit code of 0, signaling successful execution, that is considered a "true" result; if they return a nonzero exit code, signaling a failure condition, that is considered a "false" result. However, these results are not returned as a Boolean value. <tt>if command; then do something; fi</tt> will do something if the command succeeds, but there's no "true" value, only the zero exit status. So this demo uses a function that examines the exit status of the last command and prints "true" if it is 0 and "false" otherwise. The two values for the task are the <em>commands</em> <tt>true</tt> and <tt>false</tt>, which do nothing but exit with status 0 and 1, respectively. |
|||
{{works with|Bourne Again SHell}} |
|||
{{works with|Korn Shell}} |
|||
{{Works with|Z Shell}} |
|||
<syntaxhighlight lang="bash">function boolVal { |
|||
if (( ! $? )); then |
|||
echo true |
|||
else |
|||
echo false |
|||
fi |
|||
} |
|||
a=true |
|||
b=false |
|||
printf '%s and %s = %s\n' "$a" "$b" "$("$a" && "$b"; boolVal)" |
|||
printf '%s or %s = %s\n' "$a" "$b" "$("$a" || "$b"; boolVal)" |
|||
printf 'not %s = %s\n' "$a" "$(! "$a"; boolVal)"</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>true and false = false |
|||
true or false = true |
|||
not true = false</pre> |
|||
A different variety of Boolean logic is available inside arithmetic expressions, using the C convention of 0=false and nonzero=true=1: |
|||
<syntaxhighlight lang="bash">a=1 |
|||
b=0 |
|||
printf '%d and %d = %d\n' "$a" "$b" "$(( a && b ))" |
|||
printf '%d or %d = %d\n' "$a" "$b" "$(( a || b ))" |
|||
printf 'not %d = %d\n' "$a" "$(( ! a ))"</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>1 and 0 = 0 |
|||
1 or 0 = 1 |
|||
not 1 = 0</pre> |
|||
=={{header|V}}== |
=={{header|V}}== |
||
Using stack shuffles. |
Using stack shuffles. |
||
< |
<syntaxhighlight lang="v">[mylogic |
||
[get2 [dup] dip swap [dup] dip]. |
[get2 [dup] dip swap [dup] dip]. |
||
get2 and puts |
get2 and puts |
||
Line 3,853: | Line 4,219: | ||
swap not puts |
swap not puts |
||
pop |
pop |
||
].</ |
].</syntaxhighlight> |
||
Using view. |
Using view. |
||
< |
<syntaxhighlight lang="v">[mylogic |
||
[get2 [a b : a b a b] view]. |
[get2 [a b : a b a b] view]. |
||
get2 and puts |
get2 and puts |
||
Line 3,862: | Line 4,228: | ||
swap not puts |
swap not puts |
||
pop |
pop |
||
].</ |
].</syntaxhighlight> |
||
Using internal defines |
Using internal defines |
||
< |
<syntaxhighlight lang="v">[mylogic [a b] let |
||
a b and puts |
a b and puts |
||
a b or puts |
a b or puts |
||
a not puts |
a not puts |
||
].</ |
].</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">public class Program { |
||
private static void print_logic (bool a, bool b) { |
private static void print_logic (bool a, bool b) { |
||
print ("a and b is %s\n", (a && b).to_string ()); |
print ("a and b is %s\n", (a && b).to_string ()); |
||
Line 3,887: | Line 4,253: | ||
return 0; |
return 0; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Verilog}}== |
=={{header|Verilog}}== |
||
< |
<syntaxhighlight lang="verilog">module main; |
||
integer a, b; |
integer a, b; |
||
Line 3,901: | Line 4,267: | ||
$finish ; |
$finish ; |
||
end |
end |
||
endmodule</ |
endmodule</syntaxhighlight> |
||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang="vbnet">Function Test(ByVal a As Boolean, ByVal b As Boolean) |
||
Console.WriteLine("And " & a And b) |
Console.WriteLine("And " & a And b) |
||
Console.WriteLine("Or " & a Or b) |
Console.WriteLine("Or " & a Or b) |
||
Line 3,912: | Line 4,278: | ||
Console.WriteLine("And, short-circuited " & a AndAlso b) |
Console.WriteLine("And, short-circuited " & a AndAlso b) |
||
Console.WriteLine("Or, short-circuited " & a OrElse b) |
Console.WriteLine("Or, short-circuited " & a OrElse b) |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Wren has a built in Bool type which has two instances ''true'' and ''false'' which are also keywords. |
Wren has a built in Bool type which has two instances ''true'' and ''false'' which are also keywords. |
||
The Bool class overrides |
The Bool class overrides the ''!'' operator which it inherits from the Object class so that ''!true'' is false and ''!false'' is true as one would expect. |
||
Unlike some other C fanily languages, the Bool class doesn't support the operators ''&'', ''|'', ''^'' and ''~'' which, in Wren, only apply to bitwise operations on unsigned 32-bit integers. |
Unlike some other C fanily languages, the Bool class doesn't support the operators ''&'', ''|'', ''^'' and ''~'' which, in Wren, only apply to bitwise operations on unsigned 32-bit integers. |
||
However, it does support the short-circuiting ''&&'' and ''||'' logical operators as well as the conditional (or ternary) operator ''?:'' all of which behave as expected. |
However, it does support the short-circuiting ''&&'' and ''||'' logical operators as well as the conditional (or ternary) operator ''?:'' all of which behave as expected. |
||
< |
<syntaxhighlight lang="wren">var f = Fn.new { |a, b| |
||
System.print("a = %(a)") |
System.print("a = %(a)") |
||
System.print("b = %(b)") |
System.print("b = %(b)") |
||
Line 3,932: | Line 4,298: | ||
var tests = [ [true, true], [true, false], [false, true], [false, false] ] |
var tests = [ [true, true], [true, false], [false, true], [false, false] ] |
||
for (test in tests) f.call(test[0], test[1])</ |
for (test in tests) f.call(test[0], test[1])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,962: | Line 4,328: | ||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
< |
<syntaxhighlight lang="lisp">(defun logical-functions (a b) |
||
(print `(a and b = ,(and a b))) |
(print `(a and b = ,(and a b))) |
||
(print `(a or b = ,(or a b))) |
(print `(a or b = ,(or a b))) |
||
(print `(not a = ,(not a))) )</ |
(print `(not a = ,(not a))) )</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
Line 3,976: | Line 4,342: | ||
convenient to combine logical and bitwise operations. |
convenient to combine logical and bitwise operations. |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
func Logic(A, B); |
func Logic(A, B); |
||
Line 3,991: | Line 4,357: | ||
Logic(1, 1); CrLf(0); |
Logic(1, 1); CrLf(0); |
||
Logic(1, 2); CrLf(0); |
Logic(1, 2); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,003: | Line 4,369: | ||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
||
< |
<syntaxhighlight lang="xml"><xsl:template name="logic"> |
||
<xsl:param name="a" select="true()"/> |
<xsl:param name="a" select="true()"/> |
||
<xsl:param name="b" select="false()"/> |
<xsl:param name="b" select="false()"/> |
||
Line 4,009: | Line 4,375: | ||
<fo:block>a or b = <xsl:value-of select="$a or $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> |
<fo:block>not a = <xsl:value-of select="not($a)"/></fo:block> |
||
</xsl:template></ |
</xsl:template></syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Logical and/or do the logic and returns one of the ops. |
Logical and/or do the logic and returns one of the ops. |
||
< |
<syntaxhighlight lang="zkl">fcn f(a,b){a and b} |
||
fcn g(a,b){a or b} |
fcn g(a,b){a or b} |
||
fcn h(a){(not a)}</ |
fcn h(a){(not a)}</syntaxhighlight> |
||
<pre> |
<pre> |
||
f(0,1) //-->0 |
f(0,1) //-->0 |
Latest revision as of 16:59, 13 June 2024
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:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
- Task
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.
11l
F logic(a, b)
print(‘a and b: ’(a & b))
print(‘a or b: ’(a | b))
print(‘not a: ’(!a))
360 Assembly
Assembler 360 offers a full set of opcodes for logical operations: or, and, xor (exclusive or). The "not" can be done by inversing the branching: BNE (Branch Not Equal) instead of BE (Branch Equal). An othe way to perform a not is to use a xor with the true value (X'FF').
Op-codes Or And Xor --- --- --- Memory to memory OC NC XC Memory to register O N X Immediate OI NI XI
An example:
* Logical operations 04/04/2017
LOGICAL CSECT
USING LOGICAL,R15
* -- C=A and B
MVC C,A C=A
NC C,B C=A and B
* -- C=A or B
MVC C,A C=A
OC C,B C=A or B
* -- C=not A
MVC C,A C=A
XI C,X'01' C=not A
* -- if C then goto e
CLI C,X'01' if C
BE E then goto e
XPRNT =C'FALSE',5
*
E BR R14
TRUE DC X'01'
FALSE DC X'00'
A DC X'01'
B DC X'00'
C DS X
PG DC CL80' '
YREGS
END LOGICAL
- Output:
FALSE
6502 Assembly
There are no built-in boolean types; however, supporting the concept in software is trivial. Typically, the zero flag or the carry flag can act as a boolean, with zero being false and nonzero being true.
LDA myBoolean
BNE isTrue
;code that would execute if myBoolean is false, goes here.
RTS
isTrue:
;code that would execute if myBoolean is true, goes here.
RTS
Branches Based On Equality to Zero
A logical AND can easily be implemented as a nested if. Here, we'll be executing the following pseudocode. For this example, all variables are one byte in size.
if(myValue == 3 && myOtherValue == 5){
myResult = true;
}
LDA myValue
CMP #3
BNE .skip
;if we got to here, "myValue == 3" evaluated to true.
LDA myOtherValue
CMP #5
BNE .skip
;if we got to here, both "myValue == 3" and "myOtherValue" == 5 evaluated to true.
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult.
.skip:
A logical OR is somewhat similar.
if(myValue == 3 || myOtherValue == 5){
myResult = true;
}
LDA myValue
CMP #3
BEQ .doTheThing
;if not equal, check myOtherValue
LDA myOtherValue
CMP #5
BNE .skip
;if we got to here, either "myValue == 3" or "myOtherValue" == 5 evaluated to true.
.doTheThing:
STA myResult ;any nonzero value is considered TRUE, so we've stored 5 into myResult.
.skip:
Logical NOT is the easiest of all; just use the opposite branch condition.
Using Bit Shifts
Chances are, however, on an 8-bit computer like the 6502, rather than using an entire byte to represent a single variable, you're going to store up to 8 related booleans in a single byte. Variables such as these are often called "bit flags" and is very common for parameters that are passed to/from external hardware, such as joysticks, video display processors, or sound cards. Each bit typically represents a different yet related variable. For example, reading a one-button joystick returns 5 bits, one for the "fire button" and the 4 directions.
Side note: For joysticks, it's actually more common for 0 to represent pressed and 1 to represent not pressed, but that's out of the scope of this task.
For testing multiple bits, a simple BNE
or BEQ
won't cut it, as this doesn't tell you WHICH bits are 0 or 1, only that a 1 exists/doesn't exist somewhere in the byte (which, if you need that info specifically, can be a nice shortcut.)
In this example, we'll be testing the bottom 2 bits of the 8-bit variable "Flags", and we want to test if both bits are 1.
LDA flags
LSR ;test the rightmost bit.
BCC .skip
LSR ;test the bit just to the left of the one we tested prior.
BCC .skip
;your code for what happens when both of the bottom 2 bits are 1, goes here.
.skip:
Using BIT
If we're testing the top 2 bits of a byte (usually referred to as bit 7 or 6) then there's a special method we can use. The BIT instruction sets the N flag to bit 7 of the tested byte, and the V flag to bit 6 of the tested byte.
BIT myBitFlags
BMI .Bit7Set
BVS .Bit6Set
For this reason, it's a good strategy when designing a bit flags variable to put the bits you'll be testing the most in bit 7 or 6 so that you spend less time checking them.
ACL2
(defun logical-ops (a b)
(progn$ (cw "(and a b) = ~x0~%" (and a b))
(cw "(or a b) = ~x0~%" (or a b))
(cw "(not a) = ~x0~%" (not a))))
Action!
BYTE FUNC Not(BYTE a)
IF a=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
BYTE a,b,res
FOR a=0 TO 1
DO
FOR b=0 TO 1
DO
res=a AND b
PrintF("%B AND %B=%B",a,b,res)
res=a OR b
PrintF("|%B OR %B=%B",a,b,res)
res=a ! b
PrintF("|%B XOR %B=%B",a,b,res)
res=Not(a)
PrintF("|NOT %B=%B%E",a,res)
OD
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
0 AND 0=0|0 OR 0=0|0 XOR 0=0|NOT 0=1 0 AND 1=0|0 OR 1=1|0 XOR 1=1|NOT 0=1 1 AND 0=0|1 OR 0=1|1 XOR 0=1|NOT 1=0 1 AND 1=1|1 OR 1=1|1 XOR 1=0|NOT 1=0
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;
Agda
Short version
module AndOrNot where
open import Data.Bool using (Bool ; false ; true ; _∧_ ; _∨_ ; not)
open import Data.Product using (_,_ ; _×_)
test : Bool → Bool → Bool × Bool × Bool
test a b = a ∧ b , a ∨ b , not a
e.g.
test true false ⇒ false , true , false
Long version
module AndOrNot where
-- This part is to compute the values
open import Data.Bool using (Bool ; false ; true ; _∧_ ; _∨_ ; not)
open import Data.Product using (_,_ ; _×_)
test : Bool → Bool → Bool × Bool × Bool
test a b = a ∧ b , a ∨ b , not a
-- This part is to print the result
open import Agda.Builtin.IO using (IO)
open import Agda.Builtin.Unit using (⊤)
open import Data.String using (String ; _++_)
open import Data.Bool.Show using (show)
get-and-or-not-str : Bool × Bool × Bool → String
get-and-or-not-str (t₁ , t₂ , t₃) =
"a and b: " ++ (show t₁) ++ ", " ++
"a or b: " ++ (show t₂) ++ ", " ++
"not a: " ++ (show t₃)
test-str : Bool → Bool → String
test-str a b = get-and-or-not-str (test a b)
postulate putStrLn : String → IO ⊤
{-# FOREIGN GHC import qualified Data.Text as T #-}
{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-}
run : Bool → Bool → IO ⊤
run a b = putStrLn (test-str a b)
main : IO ⊤
main = run true false
--
-- This program outputs:
-- a and b: false, a or b: true, not a: false
--
Aikido
function logic(a,b) {
println("a AND b: " + (a && b))
println("a OR b: " + (a || b))
println("NOT a: " + (!a))
}
Aime
void
out(integer a, integer b)
{
o_integer(a && b);
o_byte('\n');
o_integer(a || b);
o_byte('\n');
o_integer(!a);
o_byte('\n');
}
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)
)
ALGOL W
procedure booleanOperations( logical value a, b ) ;
begin
% algol W has the usual "and", "or" and "not" operators %
write( a, " and ", b, ": ", a and b );
write( a, " or ", b, ": ", a or b );
write( " not ", a, ": ", not a );
% logical values can be compared with the = and not = operators %
% a not = b can be used for a xor b %
write( a, " xor ", b, ": ", a not = b );
write( a, " equ ", b, ": ", a = b );
end booleanOperations ;
Amazing Hopper
#include <hopper.h>
main:
a=0, b=1 // a and b have some values...
{"values A=",a,", B=",b} println
{"AND : ",a,b} and, println
{"OR : ",a,b} or, println
{"XOR : ",a,b} xor, println
{"NAND: ",a,b} nand, println
{"NOR : ",a,b} nor, println
{"NOT A: ",a}not, println
{"NOT B: ",b}not, println
x=-1,{3,3} rand array(x), mulby(10),ceil,gthan(5),mov(x)
y=-1,{3,3} rand array(y), mulby(10),ceil,gthan(5),mov(y)
{"\nArrays\nX:\n",x,"\nY:\n",y}println
{"AND :\n",x,y} and, println
{"OR :\n",x,y} or, println
{"XOR :\n",x,y} xor, println
{"NAND:\n",x,y} nand, println
{"NOR :\n",x,y} nor, println
{"NOT X :\n",x} not, println
{"NOT Y :\n",y} not, println
exit(0)
- Output:
values A=0, B=1 AND : 0 OR : 1 XOR : 1 NAND: 1 NOR : 0 NOT A: 1 NOT B: 0 Arrays X: 0 0 0 1 1 1 1 1 0 Y: 1 1 0 0 1 1 1 1 0 AND : 0 0 0 0 1 1 1 1 0 OR : 1 1 0 1 1 1 1 1 0 XOR : 1 1 0 1 0 0 0 0 0 NAND: 1 1 1 1 0 0 0 0 1 NOR : 0 0 1 0 0 0 0 0 1 NOT X : 1 1 1 0 0 0 0 0 1 NOT Y : 0 0 1 1 0 0 0 0 1
Apex
boolean a = true;
boolean b = false;
System.Debug('a AND b: ' + (a && b));
System.Debug('a OR b: ' + (a || b));
System.Debug('NOT a: ' + (!a));
System.Debug('a XOR b: ' + (a ^ b));
APL
APL represents Boolean values using 1 and 0. This function takes Boolean arguments before it and after it—which may be arrays of Booleans—and returns an array consisting of arg1 AND arg2, arg1 OR arg2, NOT arg1, arg1 NAND arg2, arg1 NOR arg2, and arg1 XOR arg2, in that order.
LOGICALOPS←{(⍺∧⍵)(⍺∨⍵)(~⍺)(⍺⍲⍵)(⍺⍱⍵)(⍺≠⍵)}
ARM Assembly
/* ARM assembly Raspberry PI */
/* program logicoper.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/* Initialized data */
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusive Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
sMessAffBin: .ascii "Register value : "
sZoneBin: .space 36,' '
.asciz "\n"
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* save 2 registers */
mov r0,#0b1100 @ binary value 1
mov r1,#0b0110 @ binary value 2
bl logicfunc
100: @ standard end of the program
mov r0,#0 @ return code
pop {fp,lr} @ restore 2 registers
mov r7,#EXIT @ request to exit program
swi 0 @ perform the system call
/******************************************************************/
/* logics functions */
/******************************************************************/
/* r0 contains the first value */
/* r1 contains the second value */
logicfunc:
push {r2,lr} @ save registers
mov r2,r0 @ save value 1 in r2
ldr r0,iAdrszMessResultAnd @ and
bl affichageMess
mov r0,r2 @ load value 1 in r0
and r0,r1
bl affichage2
ldr r0,iAdrszMessResultOr @ or
bl affichageMess
mov r0,r2
orr r0,r1
bl affichage2
ldr r0,iAdrszMessResultEor @ exclusive or
bl affichageMess
mov r0,r2
eor r0,r1
bl affichage2
ldr r0,iAdrszMessResultNot @ not
bl affichageMess
mov r0,r2
mvn r0,r1
bl affichage2
ldr r0,iAdrszMessResultClear @ bit clear
bl affichageMess
mov r0,r2
bic r0,r1
bl affichage2
100:
pop {r2,lr} @ restore registers
bx lr
iAdrszMessResultAnd: .int szMessResultAnd
iAdrszMessResultOr: .int szMessResultOr
iAdrszMessResultEor: .int szMessResultEor
iAdrszMessResultNot: .int szMessResultNot
iAdrszMessResultClear: .int szMessResultClear
/******************************************************************/
/* register display in binary */
/******************************************************************/
/* r0 contains the register */
affichage2:
push {r0,lr} /* save registers */
push {r1-r5} /* save other registers */
mrs r5,cpsr /* saves state register in r5 */
ldr r1,iAdrsZoneBin
mov r2,#0 @ read bit position counter
mov r3,#0 @ position counter of the written character
1: @ loop
lsls r0,#1 @ left shift with flags
movcc r4,#48 @ flag carry off character '0'
movcs r4,#49 @ flag carry on character '1'
strb r4,[r1,r3] @ character -> display zone
add r2,r2,#1 @ + 1 read bit position counter
add r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#8 @ 8 bits read
addeq r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#16 @ etc
addeq r3,r3,#1
cmp r2,#24
addeq r3,r3,#1
cmp r2,#31 @ 32 bits shifted ?
ble 1b @ no -> loop
ldr r0,iAdrsZoneMessBin @ address of message result
bl affichageMess @ display result
100:
msr cpsr,r5 /* restore state register */
pop {r1-r5} /* restore other registers */
pop {r0,lr}
bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registers */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read byte start position + index */
cmp r1,#0 /* if 0 it's over */
addne r2,r2,#1 /* else add 1 to the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output */
mov r7,#WRITE /* "write" system call */
swi #0 /* system call */
pop {r0,r1,r2,r7} /* restore other registers */
pop {fp,lr} /* restore 2 registers */
bx lr /* return */
Arturo
logic: function [a b][
print ["a AND b =" and? a b]
print ["a OR b =" or? a b]
print ["NOT a = " not? a]
]
logic true false
- Output:
a AND b = false a OR b = true NOT a = false
Asymptote
bool a = true;
bool b = false;
write(a & b);
write(a && b); //(with conditional evaluation of right-hand argument)
write(a | b);
write(a || b); //(with conditional evaluation of right-hand argument)
write(a ^ b);
write(!a);
AutoHotkey
a = 1
b = 0
msgbox % "a and b is " . (a && b)
msgbox % "a or b is " . (a || b)
msgbox % "not a is " . (!a)
Avail
Avail provides logical operators to cover all possibilities of a two-argument truth table. (Hence there are 12 entries below, plus the 4 ommitted for the trivial a
, b
, true
, and false
= 2^4.)
Method "logic ops_,_" is
[
a : boolean;
b : boolean;
|
Print: "not a: " ++ “¬a”;
Print: "not b: " ++ “¬b”;
Print: "a and b: " ++ “a ∧ b”;
Print: "a or b: " ++ “a ∨ b”;
Print: "a nand b: " ++ “a ↑ b”;
Print: "a nor b: " ++ “a ↓ b”;
Print: "a implies b: " ++ “a → b”; // = not a OR b
Print: "a is implied b b: " ++ “a ← b”; // = a OR not b
Print: "a does not imply b: " ++ “a ↛ b”; // = a AND not b
Print: "a is not implied by b: " ++ “a ↚ b”; // not a AND b
Print: "a xor b: " ++ “a ⊕ b”; // equivalent to a ≠ b
Print: "a biconditional b: " ++ “a ↔ b”; // equivalent to a = b
];
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
Axe
Lbl LOGIC
r₁→A
r₂→B
Disp "AND:",(A?B)▶Dec,i
Disp "OR:",(A??B)▶Dec,i
Disp "NOT:",(A?0,1)▶Dec,i
Return
Note that unlike TI-83 BASIC, the "and", "or", "xor", and "not(" tokens in Axe are bitwise operators, not logical operators.
BASIC
BASIC256
a = true
b = false
print a and b
print a or b
print a xor b
print not a
BBC BASIC
PROClogic(FALSE, FALSE)
PROClogic(FALSE, TRUE)
PROClogic(TRUE, FALSE)
PROClogic(TRUE, TRUE)
END
DEF PROClogic(a%, b%)
LOCAL @% : @% = 2 : REM Column width
PRINT a% " AND " b% " = " a% AND b% TAB(20);
PRINT a% " OR " b% " = " a% OR b% TAB(40);
PRINT a% " EOR " b% " = " a% EOR b% TAB(60);
PRINT " NOT " a% " = " NOT a%
ENDPROC
- Output:
0 AND 0 = 0 0 OR 0 = 0 0 EOR 0 = 0 NOT 0 = -1 0 AND -1 = 0 0 OR -1 = -1 0 EOR -1 = -1 NOT 0 = -1 -1 AND 0 = 0 -1 OR 0 = -1 -1 EOR 0 = -1 NOT -1 = 0 -1 AND -1 = -1 -1 OR -1 = -1 -1 EOR -1 = 0 NOT -1 = 0
Chipmunk Basic
false = 0 and any non-zero value is true
120 b1 = false 'value of 0
130 b2 = true 'value of 1
140 print b1 and b2
150 print b1 or b2
160 print b1 xor b2
170 print b1 eqv b2
180 print b1 imp b2
190 print not b2
Commodore BASIC
In Commodore BASIC the "logical" operators are actually bitwise operators; to enable the proper semantics when they're used for logic, true expressions return -1 (all bits set) and false expressions return 0 (all bits clear).
10 A = -1
20 B = 0
30 PRINT A AND B
40 PRINT A OR B
50 PRINT (A AND (NOT B)) OR ((NOT A) AND B)
60 PRINT NOT A
- Output:
0 -1 -1 0
Commodore BASIC version 7 for the C-128 added XOR, but it's a function, and for some reason was written to accept only unsigned (16-bit) numbers.
70 PRINT XOR(1, 0)
- Output:
1
GW-BASIC
PC-BASIC has no Boolean type and does not implement Boolean operators.
100 LET FALSE = 0
110 LET TRUE = -1
120 PRINT TRUE
130 PRINT FALSE
120 PRINT TRUE AND FALSE
150 PRINT TRUE OR FALSE
160 PRINT TRUE XOR FALSE
170 PRINT TRUE EQV FALSE
180 PRINT TRUE IMP FALSE
190 PRINT NOT TRUE
200 END
IS-BASIC
100 LET A=-1
110 LET B=0
120 PRINT A AND B
130 PRINT A OR B
140 PRINT (A AND(NOT B)) OR((NOT A) AND B)
150 PRINT NOT A
160 PRINT 15 BAND 4
170 PRINT 2 BOR 15
180 PRINT (A BOR B)-(A BAND B) ! xor
MSX Basic
120 b1 = false 'value of 0
130 b2 = not false 'value of -1
140 print b1 and b2
150 print b1 or b2
160 print b1 xor b2
170 print b1 eqv b2
180 print b1 imp b2
190 print not b2
QBasic
No booleans in BASIC... these are integers. -1 for True 0 for False.
b1 = -1
b2 = 0
PRINT b1 AND b2
PRINT b1 OR b2
PRINT NOT b1
Yabasic
b1 = true //value of 1
b2 = false //value of 0
print b1 and b2
print b1 or b2
print not b1
QuickBASIC
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
Quite BASIC
120 LET b1 = 0
130 LET b2 = -1
140 PRINT b1 AND b2
150 PRINT b1 OR b2
FreeBASIC
In addition to And, Or and Not FreeBASIC supports several other logical operators:
- XOr - Exclusive Or : true if both operands are different, false if they're the same
- Eqv - Equivalence : true if both operands are the same, false if they're different
- Imp - Implication : true unless the first operand is true and the second operand is false when it is false
There are also 'short-circuiting' operators:
- AndAlso - Same as AND but the second operand is only evaluated if the first is true
- OrElse - Same as OR but the second operand is only evaluated if the first is false
The following program illustrates the use of these operators:
' FB 1.05.0 Win64
Sub logicalDemo(b1 As Boolean, b2 As Boolean)
Print "b1 = "; b1
Print "b2 = "; b2
Print "b1 And b2 = "; b1 And b2
Print "b1 Or b2 = "; b1 Or b2
Print "b1 XOr b2 = "; b1 Xor b2
Print "b1 Eqv b2 = "; b1 Eqv b2
Print "b1 Imp b2 = "; b1 Imp b2
Print "Not b1 = "; Not b1
Print "b1 AndAlso b2 = "; b1 AndAlso b2
Print "b1 OrElse b2 = "; b1 OrElse b2
Print
End Sub
Dim b1 As Boolean = True
Dim b2 As Boolean = True
logicalDemo b1, b2
b2 = False
logicalDemo b1, b2
b1 = False
logicalDemo b1, b2
b2 = True
logicalDemo b1, b2
Print "Press any key to quit"
Sleep
- Output:
b1 = true b2 = true b1 And b2 = true b1 Or b2 = true b1 XOr b2 = false b1 Eqv b2 = true b1 Imp b2 = true Not b1 = false b1 AndAlso b2 = true b1 OrElse b2 = true b1 = true b2 = false b1 And b2 = false b1 Or b2 = true b1 XOr b2 = true b1 Eqv b2 = false b1 Imp b2 = false Not b1 = false b1 AndAlso b2 = false b1 OrElse b2 = true b1 = false b2 = false b1 And b2 = false b1 Or b2 = false b1 XOr b2 = false b1 Eqv b2 = true b1 Imp b2 = true Not b1 = true b1 AndAlso b2 = false b1 OrElse b2 = false b1 = false b2 = true b1 And b2 = false b1 Or b2 = true b1 XOr b2 = true b1 Eqv b2 = false b1 Imp b2 = true Not b1 = true b1 AndAlso b2 = false b1 OrElse b2 = true
bc
POSIX bc has neither Boolean values nor built-in logical operations. Thus one has to write them oneself:
/* The following three functions assume 0 is false and 1 is true */
/* And */
define a(x, y) {
return(x * y)
}
/* Or */
define o(x, y) {
return(x + y - x * y)
}
/* Not */
define n(x) {
return(1 - x)
}
define f(a, b) {
"a and b: "
a(a, b)
"a or b: "
o(a, b)
"not a: "
n(a)
}
GNU bc's extensions make this task much easier:
define logic_test(a, b) {
print "a and b: ", a && b, "\n"
print "a or b: ", a || b, "\n"
print "not a: ", !a, "\n"
}
Binary Lambda Calculus
Minimal definitions of the logical operations in lambda calculus are: and = \a\b.a b a
, or = \a\b.a a b
, not = \b\x\y.b y x
. In BLC these are 00 00 01 01 110 10 110
, or = 00 00 01 01 110 110 10
, not = 00 00 00 01 01 1110 10 110
respectively.
BQN
BQN has four logical operators: AND (`∧`), OR (`∨`), NOT (`¬`), XOR (`≠`). The function L
lists each of those results in the same order.
L←∧∾∨∾¬∾≠
∧∾∨∾¬∾≠
0 L 1
⟨ 0 1 0 1 ⟩
Bracmat
Bracmat has no boolean values. Instead, each expression has, apart from its value, also a S/F/I (SUCCEEDED/FAILED/IGNORE) feature, where the latter is used in the exceptional case that the success or failure of an expression should not influence the program flow.
The expression ~
is special in that it always fails. Most expressions only fail in exceptional cases, such as when a file cannot be opened. Match expressions stand apart from the rest and can be compared to expressions with comparison operations in other languages.
In the example below, the empty string represents 'true' and ~
represents 'false'. The binary operators &
and |
, which normally are used as the glue between expressions such as match operations, function definitions and function calls, are used as the logical operators 'and' and 'or', respectively.
( ( Logic
= x y
. '$arg:(=?x,?y)
& str
$ ( "\n(x,y)="
!arg
( ":\n"
"x and y -> "
( (!x&!y)&true
| false
)
)
( \n
"x or y -> "
( (!x|!y)&true
| false
)
)
"\nnot x -> "
(~!x&true|false)
)
)
& out$(Logic$(,))
& out$(Logic$(~,))
& out$(Logic$(,~))
& out$(Logic$(~,~))
);
- Output:
(x,y)=(,): x and y -> true x or y -> true not x -> false (x,y)=(~,): x and y -> false x or y -> true not x -> true (x,y)=(,~): x and y -> false x or y -> true not x -> false (x,y)=(~,~): x and y -> false x or y -> false not x -> true
Brat
logic = { a, b |
p "a and b: #{ a && b }"
p "a or b: #{ a || b }"
p "not a: #{ not a }"
}
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);
}
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);
}
}
}
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";
}
Clipper
Function Foo( a, b )
// a and b was defined as .F. (false) or .T. (true)
? a .AND. b
? a .OR. b
? .NOT. a, .NOT. b
Return Nil
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)
COBOL
Logical operations in COBOL are exactly the same as bitwise operations.
IDENTIFICATION DIVISION.
PROGRAM-ID. print-logic.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 result PIC 1 USAGE BIT.
LINKAGE SECTION.
01 a PIC 1 USAGE BIT.
01 b PIC 1 USAGE BIT.
PROCEDURE DIVISION USING a, b.
COMPUTE result = a B-AND b
DISPLAY "a and b is " result
COMPUTE result = a B-OR b
DISPLAY "a or b is " result
COMPUTE result = B-NOT a
DISPLAY "Not a is " result
COMPUTE result = a B-XOR b
DISPLAY "a exclusive-or b is " result
GOBACK
.
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>
Common Lisp
(defun demo-logic (a b)
(mapcar (lambda (op)
(format t "~a ~a ~a is ~a~%" a op b (eval (list op a b))))
'(and or)))
(loop for a in '(nil t) do
(format t "NOT ~a is ~a~%" a (not a))
(loop for b in '(nil t) do (demo-logic a b) (terpri)))
- Output:
NOT NIL is T NIL AND NIL is NIL NIL OR NIL is NIL NIL AND T is NIL NIL OR T is T NOT T is NIL T AND NIL is NIL T OR NIL is T T AND T is T T OR T is T
CLISP has xor, which can be added to the list of ops in demo-logic if using that implementation, but it's not part of the standard.
D
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 initializes floating point values 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);
}
- Output:
'true' is of type 'bool', 'false' is of type 'bool'; 'true' AND 'false' is false, 'true' OR 'false' is true, NOT 'true' is false. '0' is of type 'real', 'nan' is of type 'real'; '0' AND 'nan' is false, '0' OR 'nan' is true, NOT '0' is true. '0' is of type 'int', '[]' is of type 'real[]'; '0' AND '[]' is false, '0' OR '[]' is false, NOT '0' is true. '' is of type 'immutable(char)[]', '' is of type 'immutable(char)[]'; '' AND '' is false, '' OR '' is true, NOT '' is true. 'logical_operations.C' is of type 'logical_operations.C', 'null' is of type 'logical_operations.C'; 'logical_operations.C' AND 'null' is false, 'logical_operations.C' OR 'null' is true, NOT 'logical_operations.C' is false.
Dc
[ 1 q ] sT
[ 0=T 0 ] s!
[ l! x S@ l! x L@ + l! x ] s&
[ l! x S@ l! x L@ * l! x ] s|
[ 48 + P ] s.
[ Sb Sa
la l. x [ ] P lb l. x [ ] P
la lb l& x l. x [ ] P
la Lb l| x l. x [ ] P
La l! x l. x
A P
] sF
[a b a&b a|b !a] P A P
0 0 lF x
0 1 lF x
1 0 lF x
1 1 lF x
- Output:
a b a&b a|b !a 0 0 0 0 1 0 1 0 1 1 1 0 0 1 0 1 1 1 1 0
Delphi
Delphi supports all logical operators shown in § Pascal. Furthermore, the exclusive or operator xor is supported:
{ exclusive or }
writeLn(A:5, ' xor', B:6, ' yields', A xor B:7);
Beware: In Delphi the operators and, or and xor can also refer to bitwise operations.
DWScript
var a := True;
var b := False;
Print('a = ');
PrintLn(a);
Print('b = ');
PrintLn(b);
Print('a AND b: ');
PrintLn(a AND b);
Print('a OR b: ');
PrintLn(a OR b);
Print('NOT a: ');
PrintLn(NOT a);
Print('a XOR b: ');
PrintLn(a XOR b);
- Output:
a = True b = False a AND b: False a OR b: True NOT a: False a XOR b: True
Dyalect
var a = true
var b = false
print("a and b is \(a && b)")
print("a or b is \(a || b)")
print("Not a is \(!a)")
Déjà Vu
showbool a b:
!.( a b or a b and a b xor a b not a )
for a in [ false true ]:
for b in [ false true ]:
showbool a b
- Output:
true true true true false false true false true false true false false true true false true true false false false false false true
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).
EasyLang
proc logic a b . .
if a = 1 and b = 1
r1 = 1
.
if a = 1 or b = 1
r2 = 1
.
if a = 0
r3 = 1
.
print r1 & " " & r2 & " " & r3
.
logic 0 0
logic 0 1
logic 1 0
logic 1 1
ECL
LogicalOperations(BOOLEAN A,BOOLEAN B) := FUNCTION
ANDit := A AND B;
ORit := A OR B;
NOTA := NOT A;
XORit := (A OR B) AND NOT (A AND B);
DS := DATASET([{A,B,'A AND B is:',ANDit},
{A,B,'A OR B is:',ORit},
{A,B,'NOT A is:',NOTA},
{A,B,'A XOR B is:',XORit}],
{BOOLEAN AVal,BOOLEAN BVal,STRING11 valuetype,BOOLEAN val});
RETURN DS;
END;
LogicalOperations(FALSE,FALSE);
LogicalOperations(FALSE,TRUE);
LogicalOperations(TRUE,FALSE);
LogicalOperations(TRUE,TRUE);
LogicalOperations(1>2,1=1); //Boolean expressions are also valid here
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)
}
Elena
ELENA 4.x:
import extensions;
public program()
{
bool a := true;
bool b := false;
console.printLine("a and b is ", a && b);
console.printLine("a or b is ", a || b);
console.printLine("Not a is ", a.Inverted);
console.printLine("a xor b is ", a ^^ b)
}
- Output:
a and b is false a or b is true Not a is false a xor b is true
Elixir
Elixir also provides three boolean operators: or
, and
and not
. These operators are strict in the sense that they expect a boolean (true
or false
) as their first argument:
iex(1)> true and false
false
iex(2)> false or true
true
iex(3)> not false
true
or
and and
are short-circuit operators. They only execute the right side if the left side is not enough to determine the result:
Besides these boolean operators, Elixir also provides ||
, &&
and !
which accept arguments of any type. For these operators, all values except false
and nil
will evaluate to true:
(28)> nil || 23
23
iex(29)> [] || false
[]
iex(30)> nil && true
nil
iex(31)> 0 && 15
15
iex(32)> ! true
false
iex(33)> ! nil
true
iex(34)> ! 3.14
false
As a rule of thumb, use and
, or
and not
when you are expecting booleans. If any of the arguments are non-boolean, use &&
, ||
and !
.
Elm
--Open cmd and elm-repl and directly functions can be created
--Creating Functions
t=True
f=False
opand a b= a && b
opor a b= a || b
opnot a= not a
--Using the created Functions
opand t f
opor t f
opnot f
--Output will be False, True and True of type Boolean!
--end
EMal
fun logicOperations = void by logic a, logic b
writeLine("=== input values are " + a + ", " + b + " ===")
writeLine("a and b: " + (a and b))
writeLine(" a or b: " + (a or b))
writeLine(" not a: " + (not a))
end
logicOperations(false, false)
logicOperations(false, true)
logicOperations(true, false)
logicOperations(true, true)
- Output:
=== input values are ⊥, ⊥ === a and b: ⊥ a or b: ⊥ not a: ⊤ === input values are ⊥, ⊤ === a and b: ⊥ a or b: ⊤ not a: ⊤ === input values are ⊤, ⊥ === a and b: ⊥ a or b: ⊤ not a: ⊥ === input values are ⊤, ⊤ === a and b: ⊤ a or b: ⊤ not a: ⊥
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
Euphoria
procedure print_logic(integer a, integer b)
printf(1,"a and b is %d\n", a and b)
printf(1,"a or b is %d\n", a or b)
printf(1,"a xor b is %d\n", a xor b)
printf(1,"not a is %d\n", not a)
end procedure
Excel
If the values are typed in cells A1 and B1, type in the following in cell C1
=CONCATENATE($A1, " AND ", $B1, " is ", AND($A1,$B1))
In D1
=CONCATENATE($A1, " OR ", $B1, " is ", OR($A1,$B1))
In E1
=CONCATENATE(" NOT ", $A1, " is ", NOT($A1))
F#
let printLogic a b =
printfn "a and b is %b" (a && b)
printfn "a or b is %b" (a || b)
printfn "Not a is %b" (not a)
// The not-equals operator has the same effect as XOR on booleans.
printfn "a exclusive-or b is %b" (a <> b)
Factor
: logical-operators ( a b -- )
{
[ "xor is: " write xor . ]
[ "and is: " write and . ]
[ "or is: " write or . ]
[ "not is: " write drop not . ]
} 2cleave ;
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"]?
Fantom
class Main
{
static Void doOps (Bool arg1, Bool arg2)
{
echo ("$arg1 and $arg2 = ${arg1.and(arg2)}")
echo ("$arg1 or $arg2 = ${arg1.or(arg2)}")
echo ("not $arg1 = ${arg1.not}")
echo ("$arg1 xor $arg2 = ${arg1.xor(arg2)}")
}
public static Void main ()
{
[true,false].each |Bool arg1|
{
[true,false].each |Bool arg2|
{
doOps (arg1, arg2)
}
}
}
}
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 ;
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
Free Pascal
See Delphi
Frink
logical[a,b] :=
{
println["$a and $b is " + (a and b)]
println["$a or $b is " + (a or b)]
println["$a xor $b is " + (a xor b)]
println["$a nand $b is " + (a nand b)]
println["$a nor $b is " + (a nor b)]
println["not $a is " + (not a)]
}
FunL
def logical( a, b ) = println( """
a and b = ${a and b}
a or b = ${a or b}
not a = ${not a}
a xor b = ${a xor b}
""" )
for i <- [false, true], j <- [false, true] do logical( i, j )
- Output:
a and b = false a or b = false not a = true a xor b = false a and b = false a or b = true not a = true a xor b = true a and b = false a or b = true not a = false a xor b = true a and b = true a or b = true not a = false a xor b = false
FutureBasic
window 1, @"Logical Operations", (0,0,480,270)
Boolean a, b
text ,,,,, 43
print @"In FB, the Boolean constants _true or YES = 1, _false or NO = 0"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )
print @"a\tb\tand\tor\txor\tnand\tnor"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )
a = NO : b = NO : print a, b, a and b, a or b, a xor b, a nand b, a nor b
a = NO : b = YES : print a, b, a and b, a or b, a xor b, a nand b, a nor b
a = YES : b = NO : print a, b, a and b, a or b, a xor b, a nand b, a nor b
a = YES : b = YES : print a, b, a and b, a or b, a xor b, a nand b, a nor b
print
print "FB also has shorthand operator expressions"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )
print @"a\tb\t&&\t||\t^^\t^&\t^|"
print fn StringByPaddingToLength( @"", 39, @"-", 0 )
a = NO : b = NO : print a, b, a && b, a || b, a ^^ b, a ^& b, a ^| b
a = NO : b = YES : print a, b, a && b, a || b, a ^^ b, a ^& b, a ^| b
a = YES : b = NO : print a, b, a && b, a || b, a ^^ b, a ^& b, a ^| b
a = YES : b = YES : print a, b, a && b, a || b, a ^^ b, a ^& b, a ^| b
HandleEvents
In FB, the Boolean constants _true or YES = 1, _false or NO = 0 --------------------------------------- a b and or xor nand nor --------------------------------------- 0 0 0 0 0 0 -1 0 1 0 1 1 0 -2 1 0 0 1 1 1 -1 1 1 1 1 0 0 -1 FB also has shorthand operator expressions --------------------------------------- a b && || ^^ ^& ^| --------------------------------------- 0 0 0 0 0 0 -1 0 1 0 1 1 0 -2 1 0 0 1 1 1 -1 1 1 1 1 0 0 -1
GAP
Logical := function(a, b)
return [ a or b, a and b, not a ];
end;
Logical(true, true);
# [ true, true, false ]
Logical(true, false);
# [ true, false, false ]
Logical(false, true);
# [ true, false, true ]
Logical(false, false);
# [ false, false, true ]
gecho
3 4 and
3&&4
1 2 or
1||2
Genie
[indent=4]
/*
Logical operations in Genie
valac logicals.gs
./logicals true false
*/
def logicals(a:bool, b:bool)
print @"$a and $b is $(a and b)"
print @"$a or $b is $(a or b)"
print @"not $a is $(not a)"
init
a:bool = bool.parse(args[1])
b:bool = bool.parse(args[2])
logicals(a, b)
- Output:
prompt$ valac logicals.gs prompt$ ./logicals true false true and false is false true or false is true not true is false
Go
func printLogic(a, b bool) {
fmt.Println("a and b is", a && b)
fmt.Println("a or b is", a || b)
fmt.Println("not a is", !a)
}
Other operators that work on type bool are == and !=. == corresponds to the logical operation of equivalence. != corresponds to exclusive or.
Bitwise operators come into play when you have to work with byte- or bit-level data.
package main // stackoverflow.com/questions/28432398/difference-between-some-operators-golang import "fmt" func main() { // Use bitwise OR | to get the bits that are in 1 OR 2 // 1 = 00000001 // 2 = 00000010 // 1 | 2 = 00000011 = 3 fmt.Println(1 | 2) // Use bitwise OR | to get the bits that are in 1 OR 5 // 1 = 00000001 // 5 = 00000101 // 1 | 5 = 00000101 = 5 fmt.Println(1 | 5) // Use bitwise XOR ^ to get the bits that are in 3 OR 6 BUT NOT BOTH // 3 = 00000011 // 6 = 00000110 // 3 ^ 6 = 00000101 = 5 fmt.Println(3 ^ 6) // Use bitwise AND & to get the bits that are in 3 AND 6 // 3 = 00000011 // 6 = 00000110 // 3 & 6 = 00000010 = 2 fmt.Println(3 & 6) // Use bit clear AND NOT &^ to get the bits that are in 3 AND NOT 6 (order matters) // 3 = 00000011 // 6 = 00000110 // 3 &^ 6 = 00000001 = 1 fmt.Println(3 &^ 6) }
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:
[true, false].each { a -> [true, false].each { b-> logical(a, b) } }
- 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 && true = false a OR b = false || true = true NOT a = ! false = true a XOR b = false != true = true a EQV b = false == true = 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
Harbour
PROCEDURE Foo( a, b )
// a and b was defined as .F. (false) or .T. (true)
? a .AND. b
? a .OR. b
? ! a, ! b
RETURN
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
a_xor_b = a /= b
a_nxor_b = a == b
a_implies_b = a <= b -- sic!
(&&) and (||) are lazy on the second argument and therefore this operations are not symmetric:
*Main > False && undefined
False
Prelude> undefined && False
*** Exception: Prelude.undefined
Prelude> True || undefined
True
Prelude> undefined || True
*** Exception: Prelude.undefined
(<=), (<), (>=) and (>) on the other hand are strict:
Prelude> False <= undefined
*** Exception: Prelude.undefined
Prelude> undefined <= True
*** Exception: Prelude.undefined
Prelude> True < undefined
*** Exception: Prelude.undefined
Prelude> undefined < False
*** Exception: Prelude.undefined
hexiscript
fun logic a b
println "a and b = " + (a && b)
println "a or b = " + (a || b)
println " not a = " + (!a)
endfun
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
HolyC
U0 PrintLogic(Bool a, Bool b) {
Print("a and b is %d\n", a && b);
Print("a or b is %d\n", a || b);
Print("not a is %d\n", !a);
}
PrintLogic(TRUE, FALSE);
Hy
(defn logic [a b]
(print "a and b:" (and a b))
(print "a or b:" (or a b))
(print "not a:" (not a)))
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.
- Partial Sample Output
- :
... 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" ...
Insitux
Insitux treats all non-null
/false
values as truthy, which is illustrated by using placeholder keywords :a
and :b
in place of just true
to see how the different operations process them. and
and or
can accept more than two arguments but this is not demonstrated here.
(let pad (comp str (pad-right " " 10)))
(print "a b | (and a b) (or a b) (not a) (xor a b)")
(print (str* "-" 20) "+" (str* "-" 40))
(join "\n"
(for a [false :a]
b [false :b]
(... str (pad a) (pad b) "| "
(for op [and or not xor]
(pad (if (= op not) (op a) (op a b)))))))
- Output:
a b | (and a b) (or a b) (not a) (xor a b) --------------------+---------------------------------------- false false | false null true false false :b | false :b true :b :a false | false :a false :a :a :b | true :a false false
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)
)
J
J uses 0 for logical false and 1 for logical true.
aon=: *.`+.`(-.@[)`:0
Given boolean arguments, *.
is logical and, +.
is logical or, and -.
is logical not.
Additional primary logical operators include *:
(not-and), +:
(not-or), ~:
(exclusive-or) and <:
(logical implication).
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 aon b
0 0 0 1
0 1 1 1
1 1 0 0
An alternate approach, based on a probabilistic interpretation, uses *
for logical and, -.
for logical negation and derives the others: (*&.-.)
for logical or, (-.@*)
for not-and, (-.@*&.-.)
for not-or, (* *&.-. -.@*&.-.)
for exclusive or, and (*&.-. -.)~
for logical implication. You get the same results for simple truth values this way, but you also get consistent treatment for values between 0 and 1.
That said, J also supports truth valued operations on the binary representations of integers. (This is the concept of "packed binary", roughly speaking). For example 2b10001 b.
is and, 2b10111 b.
is or, 2b11110 b.
is nand, etc. (the last four bits of the control argument to b.
represent the desired binary truth table, while the prefix of that control argument in these examples specifies "packed binary"). Thus:
(2b10001 b. table/~i.4);(2b10110 b. table/~i.4);<2b10000 b. table/~i.4
┌───────────────┬───────────────┬───────────────┐
│┌─────┬───────┐│┌─────┬───────┐│┌─────┬───────┐│
││17 b.│0 1 2 3│││22 b.│0 1 2 3│││16 b.│0 1 2 3││
│├─────┼───────┤│├─────┼───────┤│├─────┼───────┤│
││0 │0 0 0 0│││0 │0 1 2 3│││0 │0 0 0 0││
││1 │0 1 0 1│││1 │1 0 3 2│││1 │0 0 0 0││
││2 │0 0 2 2│││2 │2 3 0 1│││2 │0 0 0 0││
││3 │0 1 2 3│││3 │3 2 1 0│││3 │0 0 0 0││
│└─────┴───────┘│└─────┴───────┘│└─────┴───────┘│
└───────────────┴───────────────┴───────────────┘
Jakt
fn logical_operations(anon a: bool, anon b: bool) {
println("a and b is {}", a and b)
println("a or b is {}", a or b)
println("not a is {}", not a)
}
fn main() {
let a = true
let b = false
logical_operations(a, b)
// Extra operations
println("a equals b is {}", a == b)
println("a xor b is {}", (a ^ b) == true) // == true ensures bool
}
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).
JavaScript
function logic(a,b) {
print("a AND b: " + (a && b));
print("a OR b: " + (a || b));
print("NOT a: " + (!a));
}
jq
In jq, and and or have short-circuit semantics, and can be used with non-boolean arguments.
In addition to the basic logical operators, jq has any and all filters. Versions of jq since 1.4 also have extended versions of these for working efficiently with streams.
def logic(a; b):
"\(a) and \(b) => \(a and b)",
"\(a) or \(b) => \(a or b)",
"\(a) | not => \(a | not)",
"if \(a) then true else false end => \(if a then true else false end)" ;
Example:
(false, null, []) as $a
| (false, null, {}) as $b
| logic( $a; $b )
$ jq -n -r -f logical_operations.jq
false and false => false
false or false => false
false | not => true
if false then true else false end => false
false and null => false
false or null => false
false | not => true
if false then true else false end => false
false and {} => false
false or {} => true
false | not => true
if false then true else false end => false
null and false => false
null or false => false
null | not => true
if null then true else false end => false
null and null => false
null or null => false
null | not => true
if null then true else false end => false
null and {} => false
null or {} => true
null | not => true
if null then true else false end => false
[] and false => false
[] or false => true
[] | not => false
if [] then true else false end => true
[] and null => false
[] or null => true
[] | not => false
if [] then true else false end => true
[] and {} => true
[] or {} => true
[] | not => false
if [] then true else false end => true
Julia
using Printf
function exerciselogic(a::Bool, b::Bool)
st = @sprintf " %5s" a
st *= @sprintf " %5s" b
st *= @sprintf " %5s" ~a
st *= @sprintf " %5s" a | b
st *= @sprintf " %5s" a & b
st *= @sprintf " %5s" a $ b
end
println("Julia's logical operations on Bool:")
println(" a b not or and xor")
for a in [true, false], b in [true, false]
println(exerciselogic(a, b))
end
- Output:
Julia's logical operations on Bool: a b not or and xor true true false true true false true false false true false true false true true true false true false false true false false false
Notes
This solution shows the bitwise operators in action. There are also short-circuiting or and and (||
, &&
). In addition, there are updating versions of the three binary logical operators, |=
, &=
and $=
.
Kotlin
Similar style to FreeBASIC entry:
fun logicalDemo(b1: Boolean, b2: Boolean) {
println("b1 = $b1")
println("b2 = $b2")
println("non-short-circuiting operators:")
println("b1 and b2 = ${b1 and b2}")
println("b1 or b2 = ${b1 or b2}")
println("b1 xor b2 = ${b1 xor b2}")
println("not b1 = ${!b1}")
println("short-circuiting operators:")
println("b1 && b2 = ${b1 && b2}")
println("b1 || b2 = ${b1 || b2}")
println()
}
fun main() {
logicalDemo(true, true)
logicalDemo(true, false)
logicalDemo(false, true)
logicalDemo(false, false)
}
- Output:
b1 = true b2 = true non-short-circuiting operators: b1 and b2 = true b1 or b2 = true b1 xor b2 = false not b1 = false short-circuiting operators: b1 && b2 = true b1 || b2 = true b1 = true b2 = false non-short-circuiting operators: b1 and b2 = false b1 or b2 = true b1 xor b2 = true not b1 = false short-circuiting operators: b1 && b2 = false b1 || b2 = true b1 = false b2 = true non-short-circuiting operators: b1 and b2 = false b1 or b2 = true b1 xor b2 = true not b1 = true short-circuiting operators: b1 && b2 = false b1 || b2 = true b1 = false b2 = false non-short-circuiting operators: b1 and b2 = false b1 or b2 = false b1 xor b2 = false not b1 = true short-circuiting operators: b1 && b2 = false b1 || b2 = false
Lambdatalk
{and true true true false true} -> false
{or true true true false true} -> true
{not true} -> false
langur
The logical operators in langur compare the "truthiness" of the left and right operands and do not require Booleans.
The operators and, or, nand, nor, and?, or?, nand?, nor?, xor?, and nxor? are short-circuiting.
Operators that end with ? are null propagating or "database" operators, and will return null if either operand is null. They short-circuit differently than normal operators (only if the left operand is null).
val test = fn(a, b) {
join("\n", [
"not {{a}}: {{not a}}",
"{{a}} and {{b}}: {{a and b}}",
"{{a}} nand {{b}}: {{a nand b}}",
"{{a}} or {{b}}: {{a or b}}",
"{{a}} nor {{b}}: {{a nor b}}",
"{{a}} xor {{b}}: {{a xor b}}",
"{{a}} nxor {{b}}: {{a nxor b}}",
"",
"not? {{a}}: {{not? a}}",
"{{a}} and? {{b}}: {{a and? b}}",
"{{a}} nand? {{b}}: {{a nand? b}}",
"{{a}} or? {{b}}: {{a or? b}}",
"{{a}} nor? {{b}}: {{a nor? b}}",
"{{a}} xor? {{b}}: {{a xor? b}}",
"{{a}} nxor? {{b}}: {{a nxor? b}}",
"\n",
])
}
val tests = [
[true, false],
[false, true],
[true, true],
[false, false],
# including null...
[true, null],
[null, true],
[false, null],
[null, false],
[null, null],
]
for t in tests {
write test(t[1], t[2])
}
- Output:
not true: false true and false: false true or false: true true nand false: true true nor false: false true xor false: true true nxor false: false not? true: false true and? false: false true or? false: true true nand? false: true true nor? false: false true xor? false: true true nxor? false: false not false: true false and true: false false or true: true false nand true: true false nor true: false false xor true: true false nxor true: false not? false: true false and? true: false false or? true: true false nand? true: true false nor? true: false false xor? true: true false nxor? true: false not true: false true and true: true true or true: true true nand true: false true nor true: false true xor true: false true nxor true: true not? true: false true and? true: true true or? true: true true nand? true: false true nor? true: false true xor? true: false true nxor? true: true not false: true false and false: false false or false: false false nand false: true false nor false: true false xor false: false false nxor false: true not? false: true false and? false: false false or? false: false false nand? false: true false nor? false: true false xor? false: false false nxor? false: true not true: false true and null: false true or null: true true nand null: true true nor null: false true xor null: true true nxor null: false not? true: false true and? null: null true or? null: null true nand? null: null true nor? null: null true xor? null: null true nxor? null: null not null: true null and true: false null or true: true null nand true: true null nor true: false null xor true: true null nxor true: false not? null: null null and? true: null null or? true: null null nand? true: null null nor? true: null null xor? true: null null nxor? true: null not false: true false and null: false false or null: false false nand null: true false nor null: true false xor null: false false nxor null: true not? false: true false and? null: null false or? null: null false nand? null: null false nor? null: null false xor? null: null false nxor? null: null not null: true null and false: false null or false: false null nand false: true null nor false: true null xor false: false null nxor false: true not? null: null null and? false: null null or? false: null null nand? false: null null nor? false: null null xor? false: null null nxor? false: null not null: true null and null: false null or null: false null nand null: true null nor null: true null xor null: false null nxor null: true not? null: null null and? null: null null or? null: null null nand? null: null null nor? null: null null xor? null: null null nxor? null: null
Lasso
// br is just for formatting output here
define br => '\r'
// define vars
local(a = true, b = false)
// boolean comparators.
// note, not including comparison operators which would return boolean results
'a AND b: ' + (#a && #b)
br
'a OR b: ' + (#a || #b)
br
'NOT a: ' + !#a
br
'NOT a (using not): ' + not #a
Liberty BASIC
There is no truly Boolean type. 0 = false, nonzero = true. A true value is ANY value not zero, but is usually considered to be either "1" or "-1".
False =0
True =not( False)
print " True ="; True, "False ="; False, "NB True here shown as -1"
print
print " a b AND OR XOR"
a =0: b =0: print " "; a; " "; b; " "; a and b; " "; a or b; " "; a xor b
a =0: b =1: print " "; a; " "; b; " "; a and b; " "; a or b; " "; a xor b
a =1: b =0: print " "; a; " "; b; " "; a and b; " "; a or b; " "; a xor b
a =1: b =1: print " "; a; " "; b; " "; a and b; " "; a or b; " "; a xor b
end
True =-1 False =0 NB True here shown as -1 . a b AND OR XOR 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0
LIL
# Logical operations, in LIL
set first [expr 1 == 1]
set second [expr 1 == 0]
func and-or-not {a b} {
print a $a b $b
print "a AND b" [expr $a && $b]
print "a OR b " [expr $a || $b]
print "NOT a " [expr !$a]
}
and-or-not $first $second
- Output:
prompt$ lil logicalOperations.lil a 1 b 0 a AND b 0 a OR b 1 NOT a 0
LiveCode
function boolOps p1, p2
local boolOpsResult
put p1 && "AND" && p2 && "=" && merge("[[p1 and p2]]") & cr after boolOpsResult
put p1 && "OR" && p2 && "=" && merge("[[p1 or p2]]") & cr after boolOpsResult
put "NOT" && p1 && "=" && merge("[[not p1]]") & cr after boolOpsResult
return boolOpsResult
end boolOps
Example
repeat for each item bop in "true,false"
put boolops(bop, bop) & cr after bopResult
put boolops(bop, not bop) & cr after bopResult
end repeat
put bopResult
-- results
true AND true = true
true OR true = true
NOT true = false
true AND false = false
true OR false = true
NOT true = false
false AND false = false
false OR false = false
NOT false = true
false AND true = false
false OR true = true
NOT false = true
LLVM
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)
$"FORMAT_AND" = comdat any
$"FORMAT_OR" = comdat any
$"FORMAT_NOT" = comdat any
@"FORMAT_AND" = linkonce_odr unnamed_addr constant [15 x i8] c"a and b is %d\0A\00", comdat, align 1
@"FORMAT_OR" = linkonce_odr unnamed_addr constant [14 x i8] c"a or b is %d\0A\00", comdat, align 1
@"FORMAT_NOT" = linkonce_odr unnamed_addr constant [13 x i8] c"not a is %d\0A\00", comdat, align 1
; Function Attrs: noinline nounwind optnone uwtable
define void @print_logic(i32, i32) #0 {
%3 = alloca i32, align 4 ;-- allocate b
%4 = alloca i32, align 4 ;-- allocate a
store i32 %1, i32* %3, align 4 ;-- copy parameter b
store i32 %0, i32* %4, align 4 ;-- copy parameter a
%5 = load i32, i32* %4, align 4 ;-- load a
%6 = icmp ne i32 %5, 0 ;-- is a true?
br i1 %6, label %and_true, label %and_false
and_true:
%7 = load i32, i32* %3, align 4
%8 = icmp ne i32 %7, 0
br label %and_false
and_false:
%9 = phi i1 [ false, %2 ], [ %8, %and_true ]
%10 = zext i1 %9 to i32
%11 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"FORMAT_AND", i32 0, i32 0), i32 %10)
%12 = load i32, i32* %4, align 4 ;-- load a
%13 = icmp ne i32 %12, 0 ;-- is a true?
br i1 %13, label %or_true, label %or_false
or_false:
%14 = load i32, i32* %3, align 4 ;-- load b
%15 = icmp ne i32 %14, 0 ;-- is b true?
br label %or_true
or_true:
%16 = phi i1 [ true, %and_false ], [ %15, %or_false ]
%17 = zext i1 %16 to i32
%18 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"FORMAT_OR", i32 0, i32 0), i32 %17)
%19 = load i32, i32* %4, align 4 ;-- load a
%20 = icmp ne i32 %19, 0
%21 = xor i1 %20, true
%22 = zext i1 %21 to i32
%23 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([13 x i8], [13 x i8]* @"FORMAT_NOT", i32 0, i32 0), i32 %22)
ret void
}
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4 ;-- allocate i
%2 = alloca i32, align 4 ;-- allocate j
store i32 0, i32* %1, align 4 ;-- store 0 in i
br label %loop_i
loop_i:
%3 = load i32, i32* %1, align 4 ;-- load i
%4 = icmp slt i32 %3, 2 ;-- i < 2
br i1 %4, label %loop_j_init, label %exit
loop_j_init:
store i32 0, i32* %2, align 4 ;-- store 0 in j
br label %loop_j
loop_j:
%5 = load i32, i32* %2, align 4 ;-- load j
%6 = icmp slt i32 %5, 2 ;-- j < 2
br i1 %6, label %loop_body, label %loop_i_inc
loop_body:
%7 = load i32, i32* %2, align 4 ;-- load j
%8 = load i32, i32* %1, align 4 ;-- load i
call void @print_logic(i32 %8, i32 %7)
%9 = load i32, i32* %2, align 4 ;-- load j
%10 = add nsw i32 %9, 1 ;-- increment j
store i32 %10, i32* %2, align 4 ;-- store j
br label %loop_j
loop_i_inc:
%11 = load i32, i32* %1, align 4 ;-- load i
%12 = add nsw i32 %11, 1 ;-- increment i
store i32 %12, i32* %1, align 4 ;-- store i
br label %loop_i
exit:
ret i32 0
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
- Output:
a and b is 0 a or b is 0 not a is 1 a and b is 0 a or b is 1 not a is 1 a and b is 0 a or b is 1 not a is 0 a and b is 1 a or b is 1 not a is 0
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).
Lua
function logic(a,b)
return a and b, a or b, not a
end
M2000 Interpreter
Module CheckIt {
Def Boolean A, B
Document Rep$
A=True
B=False
k=(A, B)
And=Lambda (a as Boolean, b as Boolean)-> a and b
Or=Lambda (a as Boolean, b as Boolean)-> a or b
Xor=Lambda (a as Boolean, b as Boolean)-> a xor b
Not=Lambda (a)->Not a
func=((And, "And"), (Or, "Or"), (Xor, "Xor"))
F1=Each(func)
While F1 {
M1=Each(k)
M2=Each(k)
While M1 {
While M2 {
A=Array(Array(F1), 0)
Rep$=Format$("{0} {1} {2} = {3}",Array(M1), Array$(Array(F1), 1),Array(M2), A(Array(M1), Array(M2)))+{
}
}
}
}
M1=Each(k)
While M1 {
Rep$=Format$("Not {0} = {1}",Array(M1), Not Array(M1))+{
}
}
Report Rep$
Clipboard Rep$
}
CheckIt
- Output:
True And True = True True And False = False False And True = False False And False = False True Or True = True True Or False = True False Or True = True False Or False = False True Xor True = False True Xor False = True False Xor True = True False Xor False = False Not True = False Not False = True
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
Maple
Infix and prefix operators are provided for each of and
, or
, not
as well as xor
and implies
.
f:=proc(a,b) a and b, a or b, not a; end proc:
f(true,true);
f(true,false);
f(false,true);
f(false,false);
- Output:
true, true, false false, true, false false, true, true false, false, true
Mathematica/Wolfram Language
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].
Maxima
f(a, b) := [not a, a or b, a and b];
/* to use multiple arguments, use any of these */
a and b and c and d;
a or b or c or d;
"and"(a, b, c, d);
"or"(a, b, c, d);
apply("and", [a, b, c, d]);
apply("or", [a, b, c, d]);
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)
)
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
min
(
:b :a
"xor is: " print! a b xor puts!
"and is: " print! a b and puts!
"or is: " print! a b or puts!
"not is: " print! a not puts!
) :logical-operators
Modula-2
MODULE LogicalOps;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Print(a,b : BOOLEAN);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
FormatString("a and b is %b\n", buf, a AND b);
WriteString(buf);
FormatString("a or b is %b\n", buf, a OR b);
WriteString(buf);
FormatString("not a is %b\n", buf, NOT a);
WriteString(buf);
WriteLn
END Print;
BEGIN
Print(FALSE, FALSE);
Print(FALSE, TRUE);
Print(TRUE, TRUE);
Print(TRUE, FALSE);
ReadChar
END LogicalOps.
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.
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
Nanoquery
def logic(a, b)
println "a and b: " + (a && b)
println "a or b: " + (a && b)
println "not a: " + !a
end
While this is translated from Python, Nanoquery does not allow any object to be treated as a boolean value. As a result, this function must be called with explicit boolean values.
- Output:
% import "logic.nq" % logic($true, $true) a and b: true a or b: true not a: false % logic($true, $false) a and b: false a or b: true not a: false
Neko
/**
Logical operations, in Neko
*/
/* For logical operations, values need to be explicitly treated as boolean */
/* Only null, false and 0 evaluate as false with $istrue() */
var logical = 1
if logical $print("literal 1 tests true\n") else $print("literal 1 tests false\n")
if $istrue(logical) $print("$istrue(1) tests true\n")
/* supports && logical AND, || logical OR, $not(value) the opposite of $istrue() */
if $istrue(logical) && logical > 0 $print("true path for logical AND\n")
if $istrue(logical) || logical > 1 $print("true path for logical OR\n")
if $not(logical) $print("true path for $not(1)\n") else $print("false path for $not(1)\n")
- Output:
prompt$ nekoc logical-operations.neko prompt$ neko logical-operations.n literal 1 tests false $istrue(1) tests true true path for logical AND true path for logical OR false path for $not(1)
Nemerle
using System;
using System.Console;
module Logical
{
WriteLogical(a : bool, b : bool) : void
{
WriteLine("{0} and {1} is {2}", a, b, a && b);
WriteLine("{0} or {1} is {2}", a, b, a || b);
WriteLine("not {0} is {1}", a, !a);
}
Main() : void {WriteLogical(true, false)}
}
Or, if you prefer keywords to operators import the Nemerle.English namespace to use and, or, and not.
NetRexx
/* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method logicalOperation(xL = boolean, xR = boolean) public static
say showBool(xL) 'AND' showBool(xR) '=' showBool(xL & xR) -- AND
say showBool(xL) 'OR ' showBool(xR) '=' showBool(xL | xR) -- OR
say showBool(xL) 'XOR' showBool(xR) '=' showBool(xL && xR) -- XOR
say ' ' 'NOT' showBool(xL) '=' showBool(\xL) -- NOT
say
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method showBool(bb = boolean) public static
if bb then bt = 'true '
else bt = 'false'
return bt
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
TRUE_ = (1 == 1)
FALSE_ = \TRUE_
lpairs = [ -
[TRUE_, TRUE_ ], -
[TRUE_, FALSE_], -
[FALSE_, TRUE_ ], -
[FALSE_, FALSE_] -
]
loop lx = 0 to lpairs.length - 1
lpair = lpairs[lx]
--say showBool(lpair[0]) showBool(lpair[1])
logicalOperation(lpair[0], lpair[1])
end lx
return
- Output:
true AND true = true true OR true = true true XOR true = false NOT true = false true AND false = false true OR false = true true XOR false = true NOT true = false false AND true = false false OR true = true false XOR true = true NOT false = true false AND false = false false OR false = false false XOR false = false NOT false = true
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)))
Nim
proc logic(a, b: bool) =
echo "a and b: ", a and b
echo "a or b: ", a or b
echo "not a: ", not a
echo "a xor b: ", a xor b
Nu
def ops [a b] {{A: $a, B: $b, "Not A": (not $a), OR: ($a or $b), AND: ($a and $b), XOR: ($a xor $b)}}
[true false] | each {[[true $in] [false $in]]} | flatten | each {ops $in.0 $in.1}
- Output:
╭───┬───────┬───────┬───────┬───────┬───────┬───────╮ │ # │ A │ B │ Not A │ OR │ AND │ XOR │ ├───┼───────┼───────┼───────┼───────┼───────┼───────┤ │ 0 │ true │ true │ false │ true │ true │ false │ │ 1 │ false │ true │ true │ true │ false │ true │ │ 2 │ true │ false │ false │ true │ false │ true │ │ 3 │ false │ false │ true │ false │ false │ false │ ╰───┴───────┴───────┴───────┴───────┴───────┴───────╯
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);
}
}
}
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)
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);
Oforth
: logical(b1, b2)
System.Out "and = " << b1 b2 and << cr
System.Out "or = " << b1 b2 or << cr
System.Out "xor = " << b1 b2 xor << cr
System.Out "not = " << b1 not << cr ;
OOC
Bools in ooc are just covers for C's bools and respond to the same operators.
logic: func (a: Bool, b: Bool) {
println()
"A=#{a}, B=#{b}:" println()
"AND: #{a && b}" println()
"OR: #{a || b}" println()
"NOT A: #{!a}" println()
}
main: func {
logic(true, false)
logic(true, true)
logic(false, false)
logic(false, true)
}
OpenEdge/Progress
The logical data type can have three values: true, false or unknown (represented by question mark).
FUNCTION testLogical RETURNS CHAR (
i_l1 AS LOGICAL,
i_l2 AS LOGICAL
):
RETURN
SUBSTITUTE( '&1 and &2: &3', i_l1, i_l2, i_l1 AND i_l2 ) + '~n' +
SUBSTITUTE( '&1 or &2: &3', i_l1, i_l2, i_l1 OR i_l2 ) + '~n' +
SUBSTITUTE( 'not &1: &2', i_l1, NOT i_l1 )
.
END FUNCTION.
MESSAGE
testLogical( FALSE, FALSE ) SKIP(1)
testLogical( FALSE, TRUE ) SKIP(1)
testLogical( TRUE, FALSE ) SKIP(1)
testLogical( TRUE, TRUE ) SKIP(2)
testLogical( ?, ? ) SKIP(1)
testLogical( ?, FALSE ) SKIP(1)
testLogical( ?, TRUE ) SKIP(1)
VIEW-AS ALERT-BOX.
- Output:
--------------------------- Message (Press HELP to view stack trace) --------------------------- no and no: no no or no: no not no: yes no and yes: no no or yes: yes not no: yes yes and no: no yes or no: yes not yes: no yes and yes: yes yes or yes: yes not yes: no ? and ?: ? ? or ?: ? not ?: ? ? and no: no ? or no: ? not ?: ? ? and yes: ? ? or yes: yes not ?: ? --------------------------- OK Help ---------------------------
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
PARI/GP
Note that the forms bitand()
, bitor()
, bitneg()
, and bitxor()
also exist. These apply the operator to each bit and do not short-circuit, unlike the below.
logic(a,b)={
print(a&b); \\ && is the same
print(a|b); \\ || is the same
print(!a);
};
Pascal
Nine logical operators are standard. Since Boolean is a built-in enumeration data type, all relational operators except the membership operator (in) are applicable. Moreover, Delphi and Free Pascal support the exclusive operator xor.
function logicalOperations(A, B: Boolean): Boolean;
begin
{ logical conjunction }
writeLn(A:5, ' and', B:6, ' yields', A and B:7);
{ logical disjunction }
writeLn(A:5, ' or', B:6, ' yields', A or B:7);
{ logical negation }
writeLn(' not', A:6, ' yields', not A:7);
{ logical equivalence }
writeLn(A:5, ' =', B:6, ' yields', A = B:7);
{ negation of logical equivalence }
writeLn(A:5, ' <>', B:6, ' yields', A <> B:7);
{ relational operators }
writeLn(A:5, ' <', B:6, ' yields', A < B:7);
writeLn(A:5, ' >', B:6, ' yields', A > B:7);
writeLn(A:5, ' <=', B:6, ' yields', A <= B:7);
writeLn(A:5, ' >=', B:6, ' yields', A >= B:7);
{ fulfill task requirement of writing a function: }
logicalOperations := true
end;
Furthermore, Extended Pascal (ISO standard 10206) defines two additional logical operators. The operators and_then and or_else are intended for short-circuit evaluation. However, since all actual parameters need to be evaluated prior activation of the function, it makes little sense to use/show them in the above sample code.
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.
PascalABC.NET
See Delphi
Phix
There is a builtin bool type, which is actually just an alias for integer, and a proper boolean type in builtins/ptypes.e
The operators always return 1(true) or 0(false), and treat operands of 0 as false and all other (atom) values as true.
Short-circuiting is always applied (to all "and"/"or" expressions)
Other relational operators and maths are also valid, if you wanna get clever.
function logicop(bool a, b) return {a, b, a and b, a or b, not a, a xor b, a==b, a!=b} end function printf(1," a b and or not xor == !=\n") for a=FALSE to TRUE do -- nb: TRUE to FALSE would need a "by -1". for b=FALSE to TRUE do printf(1,"%-5t %-5t %-5t %-5t %-5t %-5t %-5t %-5t\n",logicop(a,b)) end for end for
- Output:
a b and or not xor == != false false false false true false true false false true false true true true false true true false false true false true false true true true true true false false true false
Simpler version using plain integer flags:
function logiicop(integer a, b) return {a, b, a and b, a or b, not a, a xor b, a=b, a!=b} end function printf(1," a b and or not xor == !=\n") for a=0 to 1 do for b=0 to 1 do printf(1," %d %d %d %d %d %d %d %d\n",logiicop(a,b)) end for end for
- Output:
a b and or not xor == != 0 0 0 0 1 0 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 0 0 1 0
Phixmonti
/# Rosetta Code problem: https://rosettacode.org/wiki/Logical_operations
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
def logiicop var b var a
( a b a b and a b or a not a b xor a b == a b != )
enddef
def printSec
len for get print "\t" print endfor drop nl
enddef
( "a" "b" "and" "or" "not" "xor" "==" "!=" ) printSec
( 0 1 ) for dup
( 0 1 ) for
logiicop printSec
endfor
endfor
- Output:
a b and or not xor == != 0 0 0 0 1 0 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 0 0 1 0 === Press any key to exit ===
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";
}
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)) )
PL/I
logical_ops: procedure (t, u);
declare (t, u) bit (1);
put skip list (t & u);
put skip list (t | u); /* logical or */
put skip list (^t); /* logical not */
put skip list (t ^ u); /* exclusive or */
end logical_ops;
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);
PostScript
/logical{
/a exch def
/b exch def
a b and =
a b or =
a not =
}def
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)
}
Prolog
In Prolog, ',' is used for and, ';' for or and \+ for not.
?- true,true. true. ?- true,false. false. ?- true;false. true . ?- false;true. true . ?- false;false. false . ?- \+true. false. ?- \+false. true. ?- \+((true,false)). true. ?- \+((true;false)). false.
PureBasic
Procedure LogicDebug(a,b)
Debug a & b ;And
Debug a | b ;Or
Debug ~a ;Not
Debug a ! b ;XOr
EndProcedure
logicDebug(#True, #True)
logicDebug(#True, #False)
logicDebug(#False, #False)
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.
QB64
Dim As _Unsigned _Bit First, Second
First = 0: Second = 1
Print " Operator F S results "
Print " AND 1 0 "; First And Second
Print " XOR 1 0 "; First Xor Second
Print " OR 1 0 "; First Or Second
Print " NOT 1 "; Not First
Print " EQV 1 0 "; First Eqv Second
Print " IMP 1 0 "; First Imp Second
Quackery
Quackery also has the boolean words nand
and xor
.
[ iff [ say "true" ]
else [ say "false"] ] is echobool ( b --> )
[ 2dup and
say "A and B is " echobool cr
over or
say "A or B is " echobool cr
not
say "not A is " echobool cr ] is task ( A B --> )
- Output:
As a dialogue in the Quackery shell.
/O> true true task ... A and B is true A or B is true not A is false Stack empty. /O> true false task ... A and B is false A or B is true not A is false Stack empty. /O> false true task ... A and B is false A or B is true not A is true Stack empty. /O> false false task ... A and B is false A or B is false not A is true Stack empty.
R
logic <- function(a, b) {
print(a && b)
print(a || b)
print(! a)
}
logic(TRUE, TRUE)
logic(TRUE, FALSE)
logic(FALSE, FALSE)
Racket
#lang racket
(define (logic a b)
(displayln (format "a and b equals ~a" (and a b)))
(displayln (format "a or b equals ~a" (or a b)))
(displayln (format "not a equals ~a" (not a)))
(displayln (format "a nand b equals ~a" (nand a b)))
(displayln (format "a nor b equals ~a" (nor a b)))
(displayln (format "a implies b equals ~a" (implies a b)))
(displayln (format "a xor b equals ~a" (xor a b))))
Raku
(formerly Perl 6)
Raku 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 Nil !3 is False 3 ?& 10 is True 3 ?| 10 is True 3 ?^ 10 is False 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 Nil not 3 is False
Rascal
import IO;
public void logic(bool a, bool b){
println("a and b, is <a && b>");
println("a or b, is <a || b>");
println("a equivalent to b, is <a <==> b>");
println("a implies b, is <a ==> b>");
println("not a", <!a>");
}
- Output:
rascal>logic(false, false); a and b, is false a or b, is false a equivalent to b, is true a implies b, is true not a, true ok
REBOL
logics: func [a [logic!] b [logic!]] [
print ['and tab a and b]
print ['or tab a or b]
print ['not tab not a]
print ['xor tab a xor b]
print ['and~ tab and~ a b]
print ['or~ tab or~ a b]
print ['xor~ tab xor~ a b]
print ['any tab any [a b]]
print ['all tab all [a b]]
]
Example:
>> logics true false and false or true not false xor true and~ false or~ true xor~ true any true all none
Relation
program logic(x,y)
relation a, b, op, result
insert x, y, "and", x and y
insert x, y, "or", x or y
insert x, "", "not", not x
insert x, y, "xor", x xor y
print
end program
run logic(0,0)
run logic(0,1)
run logic(1,0)
run logic(1,1)
In Relation TRUE is the number 1 (or any different from 0) and FALSE 0.
ReScript
let logic = (a, b) => {
Js.log(string_of_bool(a) ++ " and " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a && b))
Js.log(string_of_bool(a) ++ " or " ++ string_of_bool(b) ++ " = " ++ string_of_bool(a || b))
}
let logic2 = (a) =>
Js.log("not(" ++ string_of_bool(a) ++ ") = " ++ string_of_bool(!a))
logic(true, true)
logic(true, false)
logic(false, true)
logic(false, false)
logic2(true)
logic2(false)
- Output:
$ bsc logical_op.res > logical_op.bs.js $ node logical_op.bs.js true and true = true true or true = true true and false = false true or false = true false and true = false false or true = true false and false = false false or false = false not(true) = false not(false) = true
Retro
: .bool ( f- ) [ "true" ] [ "false" ] if puts cr ;
: logic ( ab- )
"\na = " puts over .bool "b = " puts dup .bool
"\na and b = " puts 2dup and .bool
"\na or b = " puts over or .bool
"\nnot a = " puts not .bool ;
REXX
The REXX language's boolean values are well formed:
- 1 (true)
- 0 (false)
Any other value will raise a REXX syntax error condition.
basic boolean functions
/*REXX program demonstrates some binary (also known as bit or logical) operations.*/
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */
/* [↓] echo the X and Y values.*/
call $ 'name', "value" /*display the header (title) line. */
call $ 'x' , x /*display "x" and then the value of X.*/
call $ 'y' , y /* " "y" " " " " " Y */
/* [↓] negate the X; then the Y value.*/
call $ 'name', "negated" /*some REXXes support the ¬ character*/
call $ 'x' , \x /*display "x" and then the value of ¬X*/
call $ 'y' , \y /* " "y" " " " " " ¬Y*/
say
say
call $ @x, @y, 'AND'; do x=0 to 1; do y=0 to 1; call $ x, y, x & y; end; end
call $ @x, @y, 'OR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x | y; end; end
call $ @x, @y, 'XOR'; do x=0 to 1; do y=0 to 1; call $ x, y, x && y; end; end
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
$: parse arg @.1, @.2, @.3, @.4; hdr= length(@.1) \== 1; if hdr then say
do j=0 to hdr; _=
do k=1 for arg(); _= _ center(@.k, 7)
end /*k*/
say _
@.= copies('═', 7) /*define a new header separator line. */
end /*j*/
return
- output when using the default (internal) inputs:
name value ═══════ ═══════ x 1 y 0 name negated ═══════ ═══════ x 0 y 1 x y AND ═══════ ═══════ ═══════ 0 0 0 0 1 0 1 0 0 1 1 1 x y OR ═══════ ═══════ ═══════ 0 0 0 0 1 1 1 0 1 1 1 1 x y XOR ═══════ ═══════ ═══════ 0 0 0 0 1 1 1 0 1 1 1 0
extended boolean functions
All sixteen boolean functions could easily be shown.
/*REXX pgm demonstrates some binary (also known as bit or logical) extended operations.*/
x= 1 ; @x= ' x ' /*set the initial values of X and Y, */
y= 0 ; @y= ' y ' /* and a couple of literals for HDRs. */
/* [↓] echo the X and Y values.*/
call $ 'name', "value" /*display the header (title) line. */
call $ 'x' , x /*display "x" and then the value of X.*/
call $ 'y' , y /* " "y" " " " " " Y */
/* [↓] negate the X; then the Y value.*/
call $ 'name', "negated" /*some REXXes support the ¬ character*/
call $ 'x' , \x /*display "x" and then the value of ¬X*/
call $ 'y' , \y /* " "y" " " " " " ¬Y*/
say /*note: NXOR is also known as XNOR. */
say /*all 16 boolean operations could ···*/
/* be shown, but only the commonly ···*/
/* known functions will be shown here.*/
call $ @x, @y, 'AND' ; do x=0 to 1; do y=0 to 1; call $ x, y, x & y ; end; end
call $ @x, @y, 'NAND'; do x=0 to 1; do y=0 to 1; call $ x, y, \(x & y); end; end
call $ @x, @y, 'OR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x | y ; end; end
call $ @x, @y, 'NOR' ; do x=0 to 1; do y=0 to 1; call $ x, y, \(x | y); end; end
call $ @x, @y, 'XOR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x && y ; end; end
call $ @x, @y, 'NXOR'; do x=0 to 1; do y=0 to 1; call $ x, y, \(x && y); end; end
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
$: parse arg @.1, @.2, @.3, @.4; hdr= length(@.1) \== 1; if hdr then say
do j=0 to hdr; _=
do k=1 for arg(); _=_ center(@.k, 7)
end /*k*/
say _
@.= copies('═', 7) /*define a new separator (header) line.*/
end /*j*/
return
- output when using the default (internal) inputs:
name value ═══════ ═══════ x 1 y 0 name negated ═══════ ═══════ x 0 y 1 x y AND ═══════ ═══════ ═══════ 0 0 0 0 1 0 1 0 0 1 1 1 x y NAND ═══════ ═══════ ═══════ 0 0 1 0 1 1 1 0 1 1 1 0 x y OR ═══════ ═══════ ═══════ 0 0 0 0 1 1 1 0 1 1 1 1 x y NOR ═══════ ═══════ ═══════ 0 0 1 0 1 0 1 0 0 1 1 0 x y XOR ═══════ ═══════ ═══════ 0 0 0 0 1 1 1 0 1 1 1 0 x y NXOR ═══════ ═══════ ═══════ 0 0 1 0 1 0 1 0 0 1 1 1
Ring
x = true
y = false
see "x and y = " + (x and y) + nl
see "x or y = " + (x or y) + nl
see "not x = " + (not x) + nl
RLaB
RLaB allows for standard logic operations.
and/or/not
are synonymous with &&/||/!
. In the case when the argument is a real number (default type of argument) the default statement in the absence of if command is is the argument non-zero.
Therefore
>> x = 5
5
>> y = 0
0
>> !x
0
>> !y
1
>> x && y
0
However, if arguments to the functions are of the type integer then the functions operate bit-wise.
>> x = int(5)
5
>> y = int(0)
0
>> !x
-6
>> !y
-1
>> x && y
0
Robotic
Due to the lack of booleans, there is no way to perform logical operations in Robotic. However, bitwise operators can be used.
RPL
≪ → a b ≪ "a and b = " a b AND →STR + "a or b = " a b OR →STR + "not a = " a NOT →STR + "a xor b = " a b XOR →STR + ≫ ≫ 'LOGIC' STO
Ruby
def logic(a, b)
print 'a and b: ', a && b, "\n"
print 'a or b: ' , a || b, "\n"
print 'not a: ' , !a , "\n"
print 'a xor b: ' , a ^ b, "\n"
end
and/or/not
are synonymous with &&/||/!
albeit with lower precedence.
Rust
fn boolean_ops(a: bool, b: bool) {
println!("{} and {} -> {}", a, b, a && b);
println!("{} or {} -> {}", a, b, a || b);
println!("{} xor {} -> {}", a, b, a ^ b);
println!("not {} -> {}\n", a, !a);
}
fn main() {
boolean_ops(true, true);
boolean_ops(true, false);
boolean_ops(false, true);
boolean_ops(false, false)
}
The Boolean operators || and && are more efficient versions of | and & in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression.
Scala
In vanilla Scala:
def logical(a: Boolean, b: Boolean): Unit = {
println("and: " + (a && b))
println("or: " + (a || b))
println("not: " + !a)
}
logical(true, false)
With Scalaz:
def logical(a: Boolean, b: Boolean): IO[Unit] = for {
_ <- putStrLn("and: " ++ (a && b).shows)
_ <- putStrLn("or: " ++ (a || b).shows)
_ <- putStrLn("not: " ++ (!a).shows)
} yield ()
logical(true, false).unsafePerformIO
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))
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;
Self
true not = false.
( true && false ) = false.
( true ^^ false ) = true. "xor"
( true || false ) = true. "or"
Sidef
func logic(a, b) {
say ("a and b: ", a && b);
say ("a or b: ", a || b);
say ("a xor b: ", a ^ b);
say (" not a: ", !a);
}
logic(false, true);
- Output:
a and b: false a or b: true a xor b: true not a: true
SkookumScript
SkookumScript has a Boolean
class with two possible values: true
or false
. Conditionals such as if
expect a Boolean
type and no other types can be implicitly coerced to a Boolean
though they can be explicitly converted. Likewise Boolean
cannot be implicitly coerced to an Integer
value.
This makes a closure that takes two Boolean values. Booleans can be indicated by predicate identifier names that end with a question mark ?
.
!logic:
(a? b?)
[
println("a and b: " a and b)
println("a or b: " a or b)
println("not a: " not a)
println("a xor b: " a xor b)
println("a nand b: " a nand b)
println("a nor b: " a nor b)
println("a not xor b: " a nxor b)
]
Example call:
logic(true false)
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
Smalltalk
Logical operators "&"(and) and "|" (or) are evaluating their arg (i.e. <expr1> OP <expr2> will evaluate expr2 in any situation).
There are also non-evaluating versions named "and:" and "or:", which only evaluate expr2 if the result is not already determined by expr1.
|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.
a implies: b
a xor: b
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")
)
Stata
Stata does not have a boolean type, and uses instead 0 and 1 to denote resp. false and true.
prog def bool
args a b
di `a'&`b'
di `a'|`b'
di !`a'
end
Likewise in Mata:
function bool(a,b) {
printf("%f\n",a&b)
printf("%f\n",a|b)
printf("%f\n",!a)
}
Swift
func logic(a: Bool, b: Bool) {
println("a AND b: \(a && b)");
println("a OR b: \(a || b)");
println("NOT a: \(!a)");
}
Additionally, ^ is used for XOR and == is used for "equal to" (a.k.a. bidirectional implication).
Tcl
proc logic {a b} {
puts "a and b: [expr {$a && $b}]"
puts "a or b: [expr {$a || $b}]"
puts "not a: [expr {!$a}]"
}
Terraform
The Hashicorp Configuration Language ( HCL ) does not support user defined functions. It only supports AND, OR and NOT logical operations. HCL is not meant for generic programming but I don't see an use case for a logarithm function in a language meant to provision infrastructure either. So......
#Aamrun, August 15th 2022
variable "a" {
type = bool
default = true
}
variable "b" {
type = bool
default = false
}
output "a_and_b" {
value = var.a && var.b
}
output "a_or_b" {
value = var.a || var.b
}
output "not_a" {
value = !var.a
}
Invocation and output :
$ terraform apply -var="a=true" -var="b=false" -auto-approve No changes. Your infrastructure matches the configuration. Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed. Apply complete! Resources: 0 added, 0 changed, 0 destroyed. Outputs: a_and_b = false a_or_b = true not_a = false $
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
uBasic/4tH
uBasic/4tH does not have logical operators, but every non-zero value will be considered TRUE in conditional statements. However, comparison operators (like =, #, < and >) can be used in expressions and will return fully qualified booleans. Hence, simple arithmetic operators will do the trick just fine.
Proc _Boolean(4, 2)
Proc _Boolean(0, 2)
Proc _Boolean(2, 0)
End
_Boolean Param(2)
a@ = a@ # 0 ' Transform to true booleans
b@ = b@ # 0
print "A and B is "; a@ * b@ ' Multiplication will now do AND
print "A or B is "; a@ + b@ ' Addition will now do OR
print "not A is "; a@ = 0 ' This will invert the boolean value
print
Return
- Output:
A and B is 1 A or B is 2 not A is 0 A and B is 0 A or B is 1 not A is 1 A and B is 0 A or B is 1 not A is 0 0 OK, 0:63
UNIX Shell
The shell has at least two levels of logical operators. Conditional logic (if, while, && and || at the statement level) operates on commands; the commands are executed, and their exit status determines their value in a Boolean context. If they return an exit code of 0, signaling successful execution, that is considered a "true" result; if they return a nonzero exit code, signaling a failure condition, that is considered a "false" result. However, these results are not returned as a Boolean value. if command; then do something; fi will do something if the command succeeds, but there's no "true" value, only the zero exit status. So this demo uses a function that examines the exit status of the last command and prints "true" if it is 0 and "false" otherwise. The two values for the task are the commands true and false, which do nothing but exit with status 0 and 1, respectively.
function boolVal {
if (( ! $? )); then
echo true
else
echo false
fi
}
a=true
b=false
printf '%s and %s = %s\n' "$a" "$b" "$("$a" && "$b"; boolVal)"
printf '%s or %s = %s\n' "$a" "$b" "$("$a" || "$b"; boolVal)"
printf 'not %s = %s\n' "$a" "$(! "$a"; boolVal)"
- Output:
true and false = false true or false = true not true = false
A different variety of Boolean logic is available inside arithmetic expressions, using the C convention of 0=false and nonzero=true=1:
a=1
b=0
printf '%d and %d = %d\n' "$a" "$b" "$(( a && b ))"
printf '%d or %d = %d\n' "$a" "$b" "$(( a || b ))"
printf 'not %d = %d\n' "$a" "$(( ! a ))"
- Output:
1 and 0 = 0 1 or 0 = 1 not 1 = 0
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
].
Vala
public class Program {
private static void print_logic (bool a, bool b) {
print ("a and b is %s\n", (a && b).to_string ());
print ("a or b is %s\n", (a || b).to_string ());
print ("not a %s\n", (!a).to_string ());
}
public static int main (string[] args) {
if (args.length < 3) error ("Provide 2 arguments!");
bool a = bool.parse (args[1]);
bool b = bool.parse (args[2]);
print_logic (a, b);
return 0;
}
}
Verilog
module main;
integer a, b;
initial begin
a = 1; //true
b = 0; //false
$display(a && b); //AND
$display(a || b); //OR
$display(!a); //NOT
$finish ;
end
endmodule
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
Wren
Wren has a built in Bool type which has two instances true and false which are also keywords.
The Bool class overrides the ! operator which it inherits from the Object class so that !true is false and !false is true as one would expect.
Unlike some other C fanily languages, the Bool class doesn't support the operators &, |, ^ and ~ which, in Wren, only apply to bitwise operations on unsigned 32-bit integers.
However, it does support the short-circuiting && and || logical operators as well as the conditional (or ternary) operator ?: all of which behave as expected.
var f = Fn.new { |a, b|
System.print("a = %(a)")
System.print("b = %(b)")
System.print("!a = %(!a)")
System.print("a && b = %(a && b)")
System.print("a || b = %(a || b)")
System.print()
}
var tests = [ [true, true], [true, false], [false, true], [false, false] ]
for (test in tests) f.call(test[0], test[1])
- Output:
a = true b = true !a = false a && b = true a || b = true a = true b = false !a = false a && b = false a || b = true a = false b = true !a = true a && b = false a || b = true a = false b = false !a = true a && b = false a || b = false
XLISP
(defun logical-functions (a b)
(print `(a and b = ,(and a b)))
(print `(a or b = ,(or a b)))
(print `(not a = ,(not a))) )
XPL0
Logical operations and bitwise operations are the same. The command word 'false' = 0 and 'true' = -1. These values are produced by comparison operations, such as A>=B. Any integer not equal to zero is considered true. Real numbers cannot be used as booleans. Symbols can be used instead: & = and, ! = or, ~ = not, | = xor. Note that not 1, which is true, is $FFFFFFFE, which is also true. Despite this, it's simple and convenient to combine logical and bitwise operations.
include c:\cxpl\codes; \intrinsic 'code' declarations
func Logic(A, B);
int A, B;
[HexOut(0, A and B); ChOut(0, ^ );
HexOut(0, A or B); ChOut(0, ^ );
HexOut(0, not A); ChOut(0, ^ );
HexOut(0, A xor B);
]; \Logic
[Logic(false, false); CrLf(0);
Logic(true, false); CrLf(0);
Logic(true, true); CrLf(0);
Logic(1, 1); CrLf(0);
Logic(1, 2); CrLf(0);
]
- Output:
00000000 00000000 FFFFFFFF 00000000 00000000 FFFFFFFF 00000000 FFFFFFFF FFFFFFFF FFFFFFFF 00000000 00000000 00000001 00000001 FFFFFFFE 00000000 00000000 00000003 FFFFFFFE 00000003
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>
zkl
Logical and/or do the logic and returns one of the ops.
fcn f(a,b){a and b}
fcn g(a,b){a or b}
fcn h(a){(not a)}
f(0,1) //-->0 f(1,2) //-->2 f(True,True) //-->True f(True,False) //-->False g(0,1) //-->1 g(1,2) //-->1 g(True,True) //-->True g(True,False) //-->True h(0) //-->True h(1) //-->False h(True) //-->False h(False) //-->True
- Programming Tasks
- Basic Data Operations
- Simple
- 11l
- 360 Assembly
- 6502 Assembly
- ACL2
- Action!
- Ada
- Agda
- Aikido
- Aime
- ALGOL 68
- ALGOL W
- Amazing Hopper
- Apex
- APL
- ARM Assembly
- Arturo
- Asymptote
- AutoHotkey
- Avail
- AWK
- Axe
- BASIC
- BASIC256
- BBC BASIC
- Chipmunk Basic
- Commodore BASIC
- GW-BASIC
- IS-BASIC
- MSX Basic
- QBasic
- Yabasic
- QuickBASIC
- Quite BASIC
- FreeBASIC
- Bc
- Binary Lambda Calculus
- BQN
- Bracmat
- Brat
- C
- C sharp
- C++
- Clipper
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- D
- Dc
- Delphi
- DWScript
- Dyalect
- Déjà Vu
- E
- EasyLang
- ECL
- Efene
- Elena
- Elixir
- Elm
- EMal
- Erlang
- Euphoria
- Excel
- F Sharp
- Factor
- FALSE
- Fantom
- Forth
- Fortran
- Free Pascal
- Frink
- FunL
- FutureBasic
- GAP
- Gecho
- Genie
- Go
- Groovy
- Harbour
- Haskell
- Hexiscript
- HicEst
- HolyC
- Hy
- Icon
- Unicon
- Insitux
- Io
- J
- Jakt
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Lambdatalk
- Langur
- Lasso
- Liberty BASIC
- LIL
- LiveCode
- LLVM
- Logo
- Lua
- M2000 Interpreter
- M4
- Maple
- Mathematica
- Wolfram Language
- Maxima
- MAXScript
- Metafont
- Min
- Modula-2
- Modula-3
- MUMPS
- Nanoquery
- Neko
- Nemerle
- NetRexx
- NewLISP
- Nim
- Nu
- Objeck
- OCaml
- Octave
- Oforth
- OOC
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- PascalABC.NET
- Phix
- Phix/basics
- Phixmonti
- PHP
- PicoLisp
- PL/I
- Pop11
- PostScript
- PowerShell
- Prolog
- PureBasic
- Python
- QB64
- Quackery
- R
- Racket
- Raku
- Rascal
- REBOL
- Relation
- ReScript
- Retro
- REXX
- Ring
- RLaB
- Robotic
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Self
- Sidef
- SkookumScript
- Slate
- Slate examples needing attention
- Examples needing attention
- Smalltalk
- Standard ML
- Stata
- Swift
- Tcl
- Terraform
- Toka
- UBasic/4tH
- UNIX Shell
- V
- Vala
- Verilog
- Visual Basic .NET
- Wren
- XLISP
- XPL0
- XSLT
- Zkl
- Pages with too many expensive parser function calls