Truth table: Difference between revisions

m
(Add 8080 assembly)
m (→‎{{header|Wren}}: Minor tidy)
 
(21 intermediate revisions by 12 users not shown)
Line 19:
*   [http://www.google.co.uk/search?q=truth+table&hl=en&client=firefox-a&hs=Om7&rls=org.mozilla:en-GB:official&prmd=imvns&tbm=isch&tbo=u&source=univ&sa=X&ei=C0uuTtjuH4Wt8gOF4dmYCw&ved=0CDUQsAQ&biw=941&bih=931&sei=%20Jk-uTuKKD4Sg8QOFkPGcCw some "truth table" examples from Google].
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">T Symbol
String id
Int lbp
Int nud_bp
Int led_bp
(ASTNode -> ASTNode) nud
((ASTNode, ASTNode) -> ASTNode) led
 
F set_nud_bp(nud_bp, nud)
.nud_bp = nud_bp
.nud = nud
 
F set_led_bp(led_bp, led)
.led_bp = led_bp
.led = led
 
T Var
String name
Int value
F (name)
.name = name
[Var] vars
 
T ASTNode
Symbol& symbol
Int var_index
ASTNode? first_child
ASTNode? second_child
 
F eval()
S .symbol.id
‘(var)’
R :vars[.var_index].value
‘|’
R .first_child.eval() [|] .second_child.eval()
‘^’
R .first_child.eval() (+) .second_child.eval()
‘&’
R .first_child.eval() [&] .second_child.eval()
‘!’
R ~.first_child.eval() [&] 1
‘(’
R .first_child.eval()
E
assert(0B)
R 0
 
[String = Symbol] symbol_table
[String] tokens
V tokeni = -1
ASTNode token_node
 
F advance(sid = ‘’)
I sid != ‘’
assert(:token_node.symbol.id == sid)
:tokeni++
:token_node = ASTNode()
I :tokeni == :tokens.len
:token_node.symbol = :symbol_table[‘(end)’]
R
V token = :tokens[:tokeni]
I token[0].is_alpha()
:token_node.symbol = :symbol_table[‘(var)’]
L(v) :vars
I v.name == token
:token_node.var_index = L.index
L.break
L.was_no_break
:token_node.var_index = :vars.len
:vars.append(Var(token))
E
:token_node.symbol = :symbol_table[token]
 
F expression(rbp = 0)
ASTNode t = move(:token_node)
advance()
V left = t.symbol.nud(move(t))
L rbp < :token_node.symbol.lbp
t = move(:token_node)
advance()
left = t.symbol.led(t, move(left))
R left
 
F parse(expr_str) -> ASTNode
:tokens = re:‘\s*(\w+|.)’.find_strings(expr_str)
:tokeni = -1
:vars.clear()
advance()
R expression()
 
F symbol(id, bp = 0) -> &
I id !C :symbol_table
V s = Symbol()
s.id = id
s.lbp = bp
:symbol_table[id] = s
R :symbol_table[id]
 
F infix(id, bp)
F led(ASTNode self, ASTNode left)
self.first_child = left
self.second_child = expression(self.symbol.led_bp)
R self
symbol(id, bp).set_led_bp(bp, led)
 
F prefix(id, bp)
F nud(ASTNode self)
self.first_child = expression(self.symbol.nud_bp)
R self
symbol(id).set_nud_bp(bp, nud)
 
infix(‘|’, 1)
infix(‘^’, 2)
infix(‘&’, 3)
prefix(‘!’, 4)
 
F nud(ASTNode self)
R self
symbol(‘(var)’).nud = nud
symbol(‘(end)’)
 
F nud_parens(ASTNode self)
V expr = expression()
advance(‘)’)
R expr
symbol(‘(’).nud = nud_parens
symbol(‘)’)
 
L(expr_str) [‘!A | B’, ‘A ^ B’, ‘S | ( T ^ U )’, ‘A ^ (B ^ (C ^ D))’]
print(‘Boolean expression: ’expr_str)
print()
ASTNode p = parse(expr_str)
print(vars.map(v -> v.name).join(‘ ’)‘ : ’expr_str)
L(i) 0 .< (1 << vars.len)
L(v) vars
v.value = (i >> (vars.len - 1 - L.index)) [&] 1
print(v.value, end' ‘ ’)
print(‘: ’p.eval())
print()</syntaxhighlight>
 
{{out}}
<pre style="height: 40ex; overflow: scroll">
Boolean expression: !A | B
 
A B : !A | B
0 0 : 1
0 1 : 1
1 0 : 0
1 1 : 1
 
Boolean expression: A ^ B
 
A B : A ^ B
0 0 : 0
0 1 : 1
1 0 : 1
1 1 : 0
 
Boolean expression: S | ( T ^ U )
 
S T U : S | ( T ^ U )
0 0 0 : 0
0 0 1 : 1
0 1 0 : 1
0 1 1 : 0
1 0 0 : 1
1 0 1 : 1
1 1 0 : 1
1 1 1 : 1
 
Boolean expression: A ^ (B ^ (C ^ D))
 
A B C D : A ^ (B ^ (C ^ D))
0 0 0 0 : 0
0 0 0 1 : 1
0 0 1 0 : 1
0 0 1 1 : 0
0 1 0 0 : 1
0 1 0 1 : 0
0 1 1 0 : 0
0 1 1 1 : 1
1 0 0 0 : 1
1 0 0 1 : 0
1 0 1 0 : 0
1 0 1 1 : 1
1 1 0 0 : 0
1 1 0 1 : 1
1 1 1 0 : 1
1 1 1 1 : 0
 
</pre>
 
=={{header|8080 Assembly}}==
Line 24 ⟶ 217:
This program runs under CP/M and takes the Boolean expression on the command line.
 
<langsyntaxhighlight lang="8080asm"> ;;; CP/M truth table generator
;;; Supported operators:
;;; ~ (not), & (and), | (or), ^ (xor) and => (implies)
Line 402 ⟶ 595:
vars: equ opstk+256 ; Space for variables
vused: equ vars+256 ; Marks which variables are used
expr: equ vused+26 ; Parsed expression is stored here</langsyntaxhighlight>
 
{{out}}
Line 424 ⟶ 617:
0 1 1 | 1
1 1 1 | 1</pre>
 
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the Algol 68G specific evaluate procedure to evaluate the Boolean expressions. The expressions must therefore be infix and valid Algol 68 boolean expressions.
<langsyntaxhighlight lang="algol68"># prints the truth table of a boolean expression composed of the 26 lowercase variables a..z, #
# the boolean operators AND, OR, XOR and NOT and the literal values TRUE and FALSE #
# The evaluation is done with the Algol 68G evaluate function which is an extension #
Line 510 ⟶ 702:
DO
print truth table( expr )
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 550 ⟶ 742:
F F F T
expression>
</pre>
 
=={{header|Amazing Hopper}}==
<p>Hopper can be converted into a dedicated application, making use of macro substitution.</p>
<p>Main program:<p>
<syntaxhighlight lang="c">
#include basica/booleanos.h
 
#include <basico.h>
 
 
algoritmo
 
variables( R0,R1,R2,R3,R4,T0,T1,T2,T3,T4,T5,T6 )
 
VARS=3
preparar valores de verdad
 
preparar cabecera {
"A","B","C","|","[A=>B","&","B=>C]","=>","A=>C"
 
} enlistar en 'cabecera'
 
expresión lógica a evaluar {
 
OP=>( A, B ), :: 'R1'
OP=>( B, C ), :: 'R2'
OP&( R1, R2 ), :: 'R0'
OP=>( A, C ), :: 'R3'
OP=>( R0, R3 )
 
} :: 'R4'
 
unir columnas( tabla, tabla, separador tabla, R1, R0, R2, R4, R3 )
 
insertar cabecera y desplegar tabla
/* =============== otro ================== */
VARS=2, preparar valores de verdad
 
preparar cabecera {
"A","B","|","value: A=>B <=> ~AvB"
} enlistar en 'cabecera'
expresión lógica a evaluar {
OP<=>( OP=>(A,B), OP|(OP~(A), B) )
 
} :: 'R0'
unir columnas( tabla, tabla, separador tabla, R0 )
 
insertar cabecera y desplegar tabla
 
/* =============== otro ================== */
VARS=4, preparar valores de verdad
preparar cabecera {
"A","B","C","D","|","[~AvB","&","A=>C","&","(B","=>","(C=>D))]","=>","A=>C"
} enlistar en 'cabecera'
expresión lógica a evaluar {
OP|( OP~(A), B) :: 'R0'
OP=>(A,C) :: 'R1'
OP&( R0, R1 ) :: 'T0'
OP=>( C,D ) :: 'R2'
OP=>( B, R2 ) :: 'T2'
OP&( T0, T2 ) :: 'T3'
OP=>( T3, R1)
 
} :: 'T4'
unir columnas( tabla, tabla, separador tabla, R0, T0,R1, T3, B, T2, R2, T4, R1)
 
insertar cabecera y desplegar tabla
 
/* =============== otro ================== */
 
VARS=2, preparar valores de verdad
preparar cabecera {
"A","B","~A","~B","A&B","AvB","A^B","A=>B","A<=>B","A~&B","A~vB"
} enlistar en 'cabecera'
expresión lógica a evaluar {
OP~(A) :: 'R0'
OP~(B) :: 'R1'
OP&(A,B) :: 'T0'
OP|(A,B) :: 'T1'
OP^(A,B) :: 'T2'
OP=>(A,B) :: 'T3'
OP<=>(A,B) :: 'T4'
OP~&(A,B) :: 'T5'
OP~|(A,B) :: 'T6'
 
}
unir columnas( tabla, tabla, R0,R1,T0,T1,T2,T3,T4, T5, T6)
 
insertar cabecera y desplegar tabla
 
/* =============== otro ================== */
VARS=1, preparar valores de verdad
preparar cabecera { "A","~A" } enlistar en 'cabecera'
unir columnas( tabla, tabla, OP~(A) )
 
insertar cabecera y desplegar tabla
terminar
</syntaxhighlight>
<p>"booleano.h" header file:</p>
<syntaxhighlight lang="c">
/* BOOLEANOS.H */
#context-free preparaciondedatos
fijar separador (NULO)
 
c=""
tamaño binario (VARS)
#( lpad("0",VARS,"0") ), separar para (tabla)
#( TOTCOMB = 2^VARS )
iterar para (i=1, #(i< TOTCOMB), ++i)
i, cambiar a base(2), quitar laterales, mover a 'c',
#( lpad("0",VARS,c) ); separar para (fila)
unir filas ( tabla, tabla, fila )
 
siguiente
replicar( "|", TOTCOMB ), separar para (separador tabla)
 
retornar\\
 
#define A V(1)
#define B V(2)
#define C V(3)
#define D V(4)
#define E V(5)
#define F V(6)
#define G V(7)
#define H V(8)
// etcétera
#define V(_X_) {1}{_X_}loc2;{TOTCOMB}{0}offset2;get(tabla);xtonum
 
#define-a :: mov
 
#defn OP<=>(_X_,_Y_) #RAND; _V1_#RNDV_=0;_V2_#RNDV_=0;#ATOM#CMPLX;\
cpy(_V1_#RNDV_);\
#ATOM#CMPLX;cpy(_V2_#RNDV_);and;{_V1_#RNDV_}not;\
{_V2_#RNDV_}not;and;or; %RAND;
#defn OP=>(_X_,_Y_) #ATOM#CMPLX;not;#ATOM#CMPLX;or;
#defn OP&(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX;and;
#defn OP|(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX;or;
#defn OP^(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX;xor;
#defn OP~&(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX;nand;
#defn OP~|(_X_,_Y_) #ATOM#CMPLX;#ATOM#CMPLX;nor;
#defn OP~(_X_) #ATOM#CMPLX;not;
 
#defn variables(*) #GENCODE $$$*$$$ #LIST={#VOID};#ENDGEN
 
#define expresiónlógicaaevaluar {1}do
#synon expresiónlógicaaevaluar prepararcabecera
 
#define centrar ;padcenter;
 
#define insertarcabeceraydesplegartabla {cabecera}length;\
mov(LENTABLA); \
dim (LENTABLA) matriz rellena ("-----",vsep),\
unir filas ( cabecera, cabecera, vsep,tabla ) \
{" ",7,cabecera}, convertir a cadena, centrar,\
mover a 'cabecera'\
transformar("1","T", transformar("0","F", cabecera)) \
guardar en 'cabecera',\
imprimir( cabecera, NL )
 
#define prepararvaloresdeverdad decimales '0' \
tabla={#VOID}, fila={#VOID}, separador tabla={#VOID},\
cabecera={#VOID}, TOTCOMB=0, LENTABLA=0,\
preparacion de datos
 
/* EOF */
</syntaxhighlight>
{{out}}
<pre>
A B C | [A=>B & B=>C] => A=>C
----- ----- ----- ----- ----- ----- ----- ----- -----
F F F | T T T T T
F F T | T T T T T
F T F | T F F T T
F T T | T T T T T
T F F | F F T T F
T F T | F F T T T
T T F | T F F T F
T T T | T T T T T
 
A B | value: A=>B <=> ~AvB
----- ----- ----- -----
F F | T
F T | T
T F | T
T T | T
 
A B C D | [~AvB & A=>C & (B => (C=>D))] => A=>C
----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
F F F F | T T T T F T T T T
F F F T | T T T T F T T T T
F F T F | T T T T F T F T T
F F T T | T T T T F T T T T
F T F F | T T T T T T T T T
F T F T | T T T T T T T T T
F T T F | T T T F T F F T T
F T T T | T T T T T T T T T
T F F F | F F F F F T T T F
T F F T | F F F F F T T T F
T F T F | F F T F F T F T T
T F T T | F F T F F T T T T
T T F F | T F F F T T T T F
T T F T | T F F F T T T T F
T T T F | T T T F T F F T T
T T T T | T T T T T T T T T
 
A B ~A ~B A&B AvB A^B A=>B A<=>B A~&B A~vB
----- ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
F F T T F F F T T T T
F T T F F T T T F T F
T F F T F T T F F T F
T T F F T T F T T F F
 
A ~A
----- -----
F T
T F
 
</pre>
 
Line 568 ⟶ 996:
rules (unlike normal APL, which evaluates right-to-left).
 
<langsyntaxhighlight APLlang="apl">truth←{
op←⍉↑'~∧∨≠→('(4 3 2 2 1 0)
order←⍬⍬{
Line 612 ⟶ 1,040:
hdr←hdr,(' ',⍵,' '),[0.5]'─'
hdr⍪(,∘' '⍣(⊃⊃-/1↓¨⍴¨hdr tab))tab
}</langsyntaxhighlight>
 
{{out}}
Line 658 ⟶ 1,086:
=={{header|BASIC}}==
 
<langsyntaxhighlight basiclang="gwbasic">10 DEFINT A-Z: DATA "~",4,"&",3,"|",2,"^",2,"=>",1
20 DIM V(26),E(255),S(255),C(5),C$(5)
30 FOR I=1 TO 5: READ C$(I),C(I): NEXT
Line 727 ⟶ 1,155:
750 IF S(S-1) THEN S(S-1)=S(S) ELSE S(S-1)=-1
760 GOTO 650
770 PRINT "Missing operand": GOTO 100</langsyntaxhighlight>
 
{{out}}
Line 795 ⟶ 1,223:
=={{header|C}}==
{{trans|D}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Line 987 ⟶ 1,415:
}
return 0;
}</langsyntaxhighlight>
 
{{output}}
Line 1,041 ⟶ 1,469:
Boolean expression:
</pre>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>
 
struct var {
char name;
bool value;
};
std::vector<var> vars;
 
template<typename T>
T pop(std::stack<T> &s) {
auto v = s.top();
s.pop();
return v;
}
 
bool is_operator(char c) {
return c == '&' || c == '|' || c == '!' || c == '^';
}
 
bool eval_expr(const std::string &expr) {
std::stack<bool> sob;
for (auto e : expr) {
if (e == 'T') {
sob.push(true);
} else if (e == 'F') {
sob.push(false);
} else {
auto it = std::find_if(vars.cbegin(), vars.cend(), [e](const var &v) { return v.name == e; });
if (it != vars.cend()) {
sob.push(it->value);
} else {
int before = sob.size();
switch (e) {
case '&':
sob.push(pop(sob) & pop(sob));
break;
case '|':
sob.push(pop(sob) | pop(sob));
break;
case '!':
sob.push(!pop(sob));
break;
case '^':
sob.push(pop(sob) ^ pop(sob));
break;
default:
throw std::exception("Non-conformant character in expression.");
}
}
}
}
if (sob.size() != 1) {
throw std::exception("Stack should contain exactly one element.");
}
return sob.top();
}
 
void set_vars(int pos, const std::string &expr) {
if (pos > vars.size()) {
throw std::exception("Argument to set_vars can't be greater than the number of variables.");
}
if (pos == vars.size()) {
for (auto &v : vars) {
std::cout << (v.value ? "T " : "F ");
}
std::cout << (eval_expr(expr) ? 'T' : 'F') << '\n'; //todo implement evaluation
} else {
vars[pos].value = false;
set_vars(pos + 1, expr);
vars[pos].value = true;
set_vars(pos + 1, expr);
}
}
 
/* removes whitespace and converts to upper case */
std::string process_expr(const std::string &src) {
std::stringstream expr;
 
for (auto c : src) {
if (!isspace(c)) {
expr << (char)toupper(c);
}
}
 
return expr.str();
}
 
int main() {
std::cout << "Accepts single-character variables (except for 'T' and 'F',\n";
std::cout << "which specify explicit true or false values), postfix, with\n";
std::cout << "&|!^ for and, or, not, xor, respectively; optionally\n";
std::cout << "seperated by whitespace. Just enter nothing to quit.\n";
 
while (true) {
std::cout << "\nBoolean expression: ";
 
std::string input;
std::getline(std::cin, input);
 
auto expr = process_expr(input);
if (expr.length() == 0) {
break;
}
 
vars.clear();
for (auto e : expr) {
if (!is_operator(e) && e != 'T' && e != 'F') {
vars.push_back({ e, false });
}
}
std::cout << '\n';
if (vars.size() == 0) {
std::cout << "No variables were entered.\n";
} else {
for (auto &v : vars) {
std::cout << v.name << " ";
}
std::cout << expr << '\n';
 
auto h = vars.size() * 3 + expr.length();
for (size_t i = 0; i < h; i++) {
std::cout << '=';
}
std::cout << '\n';
 
set_vars(0, expr);
}
}
 
return 0;
}</syntaxhighlight>
{{out}}
<pre>Accepts single-character variables (except for 'T' and 'F',
which specify explicit true or false values), postfix, with
&|!^ for and, or, not, xor, respectively; optionally
seperated by whitespace. Just enter nothing to quit.
 
Boolean expression: A B ^
 
A B AB^
=========
F F F
F T T
T F T
T T F
 
Boolean expression: A B C ^ |
 
A B C ABC^|
==============
F F F F
F F T T
F T F T
F T T F
T F F T
T F T T
T T F T
T T T T
 
Boolean expression: A B C D ^ ^ ^
 
A B C D ABCD^^^
===================
F F F F F
F F F T T
F F T F T
F F T T F
F T F F T
F T F T F
F T T F F
F T T T T
T F F F T
T F F T F
T F T F F
T F T T T
T T F F F
T T F T T
T T T F T
T T T T F</pre>
 
=={{header|C sharp}}==
Line 1,047 ⟶ 1,661:
To not make it too complicated, operators are limited to a single character.<br/>
Either postfix or infix expressions are allowed. Infix expressions are converted to postfix.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 1,293 ⟶ 1,907:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,340 ⟶ 1,954:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure"> (ns clojure-sandbox.truthtables
(:require [clojure.string :as s]
[clojure.pprint :as pprint]))
Line 1,439 ⟶ 2,053:
 
(truth-table "! a | b") ;; interpreted as ! (a | b)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,452 ⟶ 2,066:
=={{header|Cowgol}}==
 
<langsyntaxhighlight lang="cowgol"># Truth table generator in Cowgol
# -
# This program will generate a truth table for the Boolean expression
Line 1,792 ⟶ 2,406:
# next configuration
vars := vars + 1;
end loop; </langsyntaxhighlight>
 
{{out}}
Line 1,846 ⟶ 2,460:
=={{header|D}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.array, std.algorithm, std.typecons;
 
struct Var {
Line 1,934 ⟶ 2,548:
writefln("%-(%s %) %s", .vars.map!(v => v.name), .expr);
setVariables(0);
}</langsyntaxhighlight>
{{out}}
<pre>Accepts single-character variables (except for 'T' and 'F',
Line 1,981 ⟶ 2,595:
=={{header|Déjà Vu}}==
{{incorrect|Déjà Vu|User input is not arbitrary but fixed to the three examples shown}}
<langsyntaxhighlight lang="dejavu">print-line lst end:
for v in reversed copy lst:
print\( v chr 9 )
Line 2,006 ⟶ 2,620:
print-truth-table [ "A" "B" ] "A ^ B" @/=
print-truth-table [ "S" "T" "U" ] "S | (T ^ U)" @stu
print-truth-table [ "A" "B" "C" "D" ] "A ^ (B ^ (C ^ D))" @abcd</langsyntaxhighlight>
{{out}}
<pre>A B A ^ B
Line 2,045 ⟶ 2,659:
=={{header|Factor}}==
Postfix is a natural choice. That way, we can use <code>(eval)</code> to to evaluate the expressions without much fuss.
<langsyntaxhighlight lang="factor">USING: arrays combinators eval formatting io kernel listener
math.combinatorics prettyprint qw sequences splitting
vocabs.parser ;
Line 2,102 ⟶ 2,716:
add-col print-table drop ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 2,141 ⟶ 2,755:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Truth_table this] page you can see the solution of this task.}}
 
'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Truth table 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
'''Test case 1'''
 
The following example produces the logical negation table:
 
[[File:Fōrmulæ - Truth table 02.png]]
 
[[File:Fōrmulæ - Truth table 03.png]]
 
'''Test case 2'''
 
The following example produces the logical conjunction table:
 
[[File:Fōrmulæ - Truth table 04.png]]
 
[[File:Fōrmulæ - Truth table 05.png]]
 
'''Test case 3'''
 
Because there is no restrictions about the mapping expression, it can be an array of expressions involving the arguments.
 
The following example produces the truth table for logical conjunction, disjunction, conditional, equivalence and exclusive disjunction:
 
[[File:Fōrmulæ - Truth table 06.png]]
 
[[File:Fōrmulæ - Truth table 07.png]]
 
'''Test case 4'''
 
In the following example, the truth table is used to show that a boolean formula is a tautology:
 
[[File:Fōrmulæ - Truth table 08.png]]
 
[[File:Fōrmulæ - Truth table 09.png]]
 
=={{header|Go}}==
Expression parsing and evaluation taken from the Arithmetic evaluation task. Operator precedence and association are that of the Go language, and are determined by the library parser. The unary ^ is first, then &, then | and ^ associating left to right. Note also that the symbols &, |, and ^ operate bitwise on integer types in Go, but here since we implement our own evaluator we can apply them to the type of bool.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,291 ⟶ 2,939:
return false, errors.New(fmt.Sprintf("%v unsupported", i))
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,328 ⟶ 2,976:
Uses operators "&", "|", "!", "^" (xor), "=>" (implication); all other words are interpreted as variable names.
 
<langsyntaxhighlight lang="haskell">import Control.Monad (mapM, foldM, forever)
import Data.List (unwords, unlines, nub)
import Data.Maybe (fromJust)
Line 2,361 ⟶ 3,009:
colWidth = max 6 $ maximum $ map length (head tbl)
main = forever $ getLine >>= putStrLn . truthTable</langsyntaxhighlight>
 
{{Out}}
Line 2,388 ⟶ 3,036:
 
Translation from infix notation to RPN using Parsec:
<langsyntaxhighlight lang="haskell">{-# LANGUAGE FlexibleContexts #-}
import Text.Parsec
 
Line 2,400 ⟶ 3,048:
many1 alphaNum
op1 s = (\x -> unwords [x, s]) <$ string s
op2 s = (\x y -> unwords [x, y, s]) <$ string s</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight lang="haskell">λ> putStr $ truthTable $ toRPN "(Human => Mortal) & (Socratus => Human) => (Socratus => Mortal)"
 
Human Mortal Socratus result
Line 2,413 ⟶ 3,061:
False True False True
False False True True
False False False True </langsyntaxhighlight>
 
=={{header|J}}==
Line 2,419 ⟶ 3,067:
Implementation:
 
<langsyntaxhighlight lang="j">truthTable=:3 :0
assert. -. 1 e. 'data expr names table' e.&;: y
names=. ~. (#~ _1 <: nc) ;:expr=. y
Line 2,425 ⟶ 3,073:
(names)=. |:data
(' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".expr
)</langsyntaxhighlight>
 
The argument is expected to be a valid boolean J sentence which, among other things, does not use any of the words used within this implementation (but any single-character name is valid).
Line 2,431 ⟶ 3,079:
Example use:
 
<langsyntaxhighlight lang="j"> truthTable '-.b'
b -.b
0 1
Line 2,462 ⟶ 3,110:
1 0 1 1
1 1 0 1
1 1 1 1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.8+}}
This takes an expression from the command line in reverse Polish notation. The supported operators are & | ^ ! and you probably need to escape them so that your shell doesn't interpret them. As an exercise for the reader, you could make it prompt the user for input (which would avoid the escaping issue), or accept infix expressions (see other examples here for how to turn infix into RPN).
<langsyntaxhighlight lang="java">import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
Line 2,584 ⟶ 3,232:
return stack.pop();
}
}</langsyntaxhighlight>
{{out}}
Note that the escape character is ^ for Windows
Line 2,619 ⟶ 3,267:
=={{header|JavaScript}}==
Actually a HTML document. Save as a .html document and double-click it. You should be fine.
<langsyntaxhighlight lang="javascript"><!DOCTYPE html><html><head><title>Truth table</title><script>
var elem,expr,vars;
function isboolop(chr){return "&|!^".indexOf(chr)!=-1;}
Line 2,678 ⟶ 3,326:
return stack[0];
}
</script></head><body onload="printtruthtable()"></body></html></langsyntaxhighlight>
{{Out|Output in browser window after entering "AB^"}}
<pre>A B AB^
Line 2,695 ⟶ 3,343:
T T F T
T T T T</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
This entry uses a PEG ([https://en.wikipedia.org/wiki/Parsing_expression_grammar Parsing Expression Grammar]) approach
to the task. In effect, a PEG grammar for logic expressions
is transcribed into a jq program for parsing and
evaluating the truth values of such expressions.
 
The PEG grammar for logic expressions used here is essentially as follows:
<pre>
expr = (primary '=>' primary) / e1
e1 = e2 (('or' / 'xor') e2)*
e2 = e3 ('and' e3)*
e3 = 'not'? primary
primary = Var / boolean / '(' expr ')'
boolean = 'true' / 'false'
</pre>
 
where Var is a string matching the regex ^[A-Z][a-zA-Z0-9]*$
 
Notice that this grammar binds '=>' most tightly, and uses `not` as a
prefix operator.
 
The PEG grammar above is transcribed and elaborated in the jq function
`expr` below. For details about this approach, see for example
[[Compiler/Verifying_syntax#jq]]. That entry also
contains the jq PEG library that is referenced
in the 'include' statement at the beginning of the
jq program shown below.
 
====Parsing====
<syntaxhighlight lang=jq>
include "peg"; # see [[:Category:jq/peg.jq]
 
def expr:
def Var : parse("[A-Z][a-zA-Z0-9]*");
 
def boolean : (literal("true") // literal("false"))
| .result[-1] |= fromjson;
 
def primary : ws
| (Var
// boolean
// box(q("(") | expr | q(")"))
)
| ws;
 
def e3 : ws | (box(literal("not") | primary) // primary);
def e2 : box(e3 | star(literal("and") | e3)) ;
def e1 : box(e2 | star((literal("or") // literal("xor")) | e2)) ;
def e0 : box(primary | literal("=>") | primary) // e1;
 
ws | e0 | ws;
 
def statement:
{remainder: .} | expr | eos;
</syntaxhighlight>
 
====Evaluation====
<syntaxhighlight lang=jq>
# Evaluate $Expr in the context of {A,B,....}
def eval($Expr):
if $Expr|type == "boolean" then $Expr
elif $Expr|type == "string" then getpath([$Expr])
elif $Expr|length == 1 then eval($Expr[0])
elif $Expr|(length == 2 and first == "not") then eval($Expr[-1])|not
elif $Expr|(length == 3 and .[1] == "or") then eval($Expr[0]) or eval($Expr[2])
elif $Expr|(length == 3 and .[1] == "xor")
then eval($Expr[0]) as $x
| eval($Expr[2]) as $y
| ($x and ($y|not)) or ($y and ($x|not))
elif $Expr|(length == 3 and .[1] == "and") then eval($Expr[0]) and eval($Expr[2])
elif $Expr|(length == 3 and .[1] == "=>") then (eval($Expr[0])|not) or eval($Expr[2])
else $Expr | error
end;
</syntaxhighlight>
====Truth Tables====
<syntaxhighlight lang=jq>
# input: a list of strings
# output: a stream of objects representing all possible true/false combinations
# Each object has the keys specified in the input.
def vars2tf:
if length == 0 then {}
else .[0] as $k
| ({} | .[$k] = (true,false)) + (.[1:] | vars2tf)
end;
 
# If the input is a string, then echo it;
# otherwise emit T or F
def TF:
if type == "string" then .
elif . then "T"
else "F"
end;
 
# Extract the distinct variable names from the parse tree.
def vars: [.. | strings | select(test("^[A-Z]"))] | unique;
 
def underscore:
., (length * "_");
 
</syntaxhighlight>
====Examples====
<syntaxhighlight lang=jq>
def tests: [
"A xor B",
"notA",
"A and B",
"A and B or C",
"A=>(notB)",
"A=>(A => (B or A))",
"A xor B and C"
];
 
def tables:
tests[] as $test
| ($test | statement | .result)
| . as $result
| vars as $vars
| ($vars + [" ", $test] | join(" ") | underscore),
(($vars | vars2tf)
| ( [.[], " ", eval($result) | TF] | join(" ")) ),
""
;
 
tables
</syntaxhighlight>
{{output}}
<pre>
A B A xor B
_____________
T T F
F T T
T F T
F F F
 
A notA
________
T F
F T
 
A B A and B
_____________
T T T
F T F
T F F
F F F
 
A B C A and B or C
____________________
T T T T
F T T T
T F T T
F F T T
T T F T
F T F F
T F F F
F F F F
 
A B A=>(notB)
_______________
T T F
F T T
T F T
F F T
 
A B A=>(A => (B or A))
________________________
T T T
F T T
T F T
F F T
 
A B C A xor B and C
_____________________
T T T F
F T T T
T F T T
F F T F
T T F T
F T F F
T F F T
F F F F
</pre>
 
=={{header|Julia}}==
'''Module''':
<langsyntaxhighlight lang="julia">module TruthTable
 
using Printf
Line 2,740 ⟶ 3,575:
end
 
end # module TruthTable</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">TruthTable.@table !a
TruthTable.@table a | b
TruthTable.@table (a ⊻ b) | (c & a)
TruthTable.@table (a & b) | (c ⊻ d)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,788 ⟶ 3,623:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
import java.util.Stack
Line 2,861 ⟶ 3,696:
setVariables(0)
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,923 ⟶ 3,758:
This at first seems trivial, given our lovely 'eval' function. However it is complicated by LB's use of 'non-zero' for 'true', and by the requirements of accepting different numbers and names of variables.
My program assumes all space-separated words in the expression$ are either a logic-operator, bracket delimiter, or variable name. Since a truth table for 8 or more variables is of silly length, I regard that as a practical limit.
<syntaxhighlight lang="lb">
<lang lb>
print
print " TRUTH TABLES"
Line 3,015 ⟶ 3,850:
end if
end function
</syntaxhighlight>
</lang>
<pre>
Too_High and Fuel_Out
Line 3,038 ⟶ 3,873:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">VariableNames[data_] := Module[ {TokenRemoved},
TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}];
Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]]
Line 3,050 ⟶ 3,885:
Join[List[Flatten[{VariableNames[BooleanEquation],BooleanEquation}]],
Flatten[{#/.Rule[x_,y_] -> y,ReplaceAll[ToExpression[BooleanEquation],#]}]&/@TestDataSet]//Grid
]</langsyntaxhighlight>
 
Example usage:
<pre>TruthTable["V ~Xor~ (B ~Xor~ (K ~Xor~ D ) )"]
Line 3,074 ⟶ 3,908:
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">/* Maxima already has the following logical operators
=, # (not equal), not, and, or
define some more and set 'binding power' (operator
Line 3,122 ⟶ 3,956:
gen_table('(Jim and (Spock xor Bones) or Scotty));
gen_table('(A => (B and A)));
gen_table('(V xor (B xor (K xor D ) )));</langsyntaxhighlight>
 
OUtput of the last example:
<syntaxhighlight lang="text">
[ V B K D V xor (B xor (K xor D)) ]
[ ]
Line 3,159 ⟶ 3,993:
[ ]
[ false false false false false ]
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
{{trans|Kotlin}}
This is an adaptation of Kotlin version, using the same rules and the same algorithm, but with a different representation of expressions. The result is identical.
 
<syntaxhighlight lang="nim">import sequtils, strutils, sugar
 
# List of possible variables names.
const VarChars = {'A'..'E', 'G'..'S', 'U'..'Z'}
 
type
 
Expression = object
names: seq[char] # List of variables names.
values: seq[bool] # Associated values.
formula: string # Formula as a string.
 
 
proc initExpression(str: string): Expression =
## Build an expression from a string.
for ch in str:
if ch in VarChars and ch notin result.names:
result.names.add ch
result.values.setLen(result.names.len)
result.formula = str
 
 
template apply(stack: seq[bool]; op: (bool, bool) -> bool): bool =
## Apply an operator on the last two operands of an evaluation stack.
## Needed to make sure that pops are done (avoiding short-circuit optimization).
let op2 = stack.pop()
let op1 = stack.pop()
op(op1, op2)
 
 
proc evaluate(expr: Expression): bool =
## Evaluate the current expression.
 
var stack: seq[bool] # Evaluation stack.
 
for e in expr.formula:
stack.add case e
of 'T': true
of 'F': false
of '!': not stack.pop()
of '&': stack.apply(`and`)
of '|': stack.apply(`or`)
of '^': stack.apply(`xor`)
else:
if e in VarChars: expr.values[expr.names.find(e)]
else:
raise newException(
ValueError, "Non-conformant character in expression: '$#'.".format(e))
 
if stack.len != 1:
raise newException(ValueError, "Ill-formed expression.")
result = stack[0]
 
 
proc setVariables(expr: var Expression; pos: Natural) =
## Recursively set the variables.
## When all the variables are set, launch the evaluation of the expression
## and print the result.
 
assert pos <= expr.values.len
 
if pos == expr.values.len:
# Evaluate and display.
let vs = expr.values.mapIt(if it: 'T' else: 'F').join(" ")
let es = if expr.evaluate(): 'T' else: 'F'
echo vs, " ", es
 
else:
# Set values.
expr.values[pos] = false
expr.setVariables(pos + 1)
expr.values[pos] = true
expr.setVariables(pos + 1)
 
 
echo "Accepts single-character variables (except for 'T' and 'F',"
echo "which specify explicit true or false values), postfix, with"
echo "&|!^ for and, or, not, xor, respectively; optionally"
echo "seperated by spaces or tabs. Just enter nothing to quit."
 
while true:
# Read formula and create expression.
stdout.write "\nBoolean expression: "
let line = stdin.readLine.toUpperAscii.multiReplace((" ", ""), ("\t", ""))
if line.len == 0: break
var expr = initExpression(line)
if expr.names.len == 0: break
 
# Display the result.
let vs = expr.names.join(" ")
echo '\n', vs, " ", expr.formula
let h = vs.len + expr.formula.len + 2
echo repeat('=', h)
expr.setVariables(0)</syntaxhighlight>
 
{{out}}
Sample session:
<pre>Accepts single-character variables (except for 'T' and 'F',
which specify explicit true or false values), postfix, with
&|!^ for and, or, not, xor, respectively; optionally
seperated by spaces or tabs. Just enter nothing to quit.
 
Boolean expression: A B ^
 
A B AB^
=========
F F F
F T T
T F T
T T F
 
Boolean expression: A B C ^ |
 
A B C ABC^|
==============
F F F F
F F T T
F T F T
F T T F
T F F T
T F T T
T T F T
T T T T
 
Boolean expression: A B C D ^ ^ ^
 
A B C D ABCD^^^
===================
F F F F F
F F F T T
F F T F T
F F T T F
F T F F T
F T F T F
F T T F F
F T T T T
T F F F T
T F F T F
T F T F F
T F T T T
T T F F F
T T F T T
T T T F T
T T T T F
 
Boolean expression: </pre>
 
=={{header|PARI/GP}}==
Line 3,165 ⟶ 4,150:
 
It would be easy to modify the program to take <code>+</code> for XOR instead.
<langsyntaxhighlight lang="parigp">vars(P)={
my(v=List(),x);
while(type(P)=="t_POL",
Line 3,187 ⟶ 4,172:
};
truthTable("x+y") \\ OR
truthTable("x*y") \\ AND</langsyntaxhighlight>
{{out}}
<pre>000
Line 3,202 ⟶ 4,187:
{{trans|C}}
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
<lang Pascal>
program TruthTables;
const
Line 3,437 ⟶ 4,422:
end;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,493 ⟶ 4,478:
=={{header|Perl}}==
Note: can't process stuff like "X xor Y"; "xor" would be treated as a variable name here.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
sub truth_table {
Line 3,513 ⟶ 4,498:
truth_table 'A ^ A_1';
truth_table 'foo & bar | baz';
truth_table 'Jim & (Spock ^ Bones) | Scotty';</langsyntaxhighlight>{{out}}<pre>
A A_1 A ^ A_1
----------------------------------------
Line 3,541 ⟶ 4,526:
=={{header|Phix}}==
Expression parsing and evaluation similar to that in the Arithmetic evaluation task.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence opstack = {}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
object token
<span style="color: #008080;">constant</span> <span style="color: #000000;">bFT</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span> <span style="color: #000080;font-style:italic;">-- true: use F/T, false: use 0/1, as next</span>
object op = 0 -- 0 = none
string s -- the expression being parsed
integer sidx -- idx to ""
integer ch -- s[sidx]
<span style="color: #008080;">function</span> <span style="color: #000000;">fmt</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
procedure err(string msg)
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bFT</span><span style="color: #0000FF;">?{</span><span style="color: #008000;">"F"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"T"</span><span style="color: #0000FF;">}:{</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">})[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg})
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
{} = wait_key()
abort(0)
end procedure
<span style="color: #004080;">sequence</span> <span style="color: #000000;">opstack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
procedure nxtch()
<span style="color: #004080;">object</span> <span style="color: #000000;">token</span><span style="color: #0000FF;">,</span>
sidx += 1
<span style="color: #000000;">op</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- 0 = none</span>
ch = iff(sidx>length(s)?-1:s[sidx])
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #000080;font-style:italic;">-- the expression being parsed</span>
end procedure
<span style="color: #004080;">integer</span> <span style="color: #000000;">sidx</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- idx to ""</span>
<span style="color: #000000;">ch</span> <span style="color: #000080;font-style:italic;">-- s[sidx]</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">err</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n%s^ %s\n\nPressEnter..."</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">nxtch</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">sidx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)?-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">skipspaces</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" \t\r\n"</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">nxtch</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">skipspaces</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"()!"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">token</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">..</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">nxtch</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">else</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">tokstart</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sidx</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">token</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"eof"</span> <span style="color: #008080;">return</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">nxtch</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #008000;">'A'</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">token</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">tokstart</span><span style="color: #0000FF;">..</span><span style="color: #000000;">sidx</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Match</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">token</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">t</span> <span style="color: #008080;">then</span> <span style="color: #000000;">err</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">&</span><span style="color: #008000;">" expected"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">PopFactor</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">opstack</span><span style="color: #0000FF;">[$]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"not"</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">opstack</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">op</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">opstack</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">opstack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">opstack</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">opstack</span><span style="color: #0000FF;">[$],</span><span style="color: #000000;">op</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">op</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">names</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- {"false","true",...}</span>
<span style="color: #000000;">flags</span> <span style="color: #000080;font-style:italic;">-- { 0, 1, ,...}</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">PushFactor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">PopFactor</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">names</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">names</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">opstack</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">opstack</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">PushOp</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">PopFactor</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">op</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">Expr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Factor</span><span style="color: #0000FF;">()</span>
procedure skipspaces()
<span style="color: #008080;">if</span> <span style="color: #000000;">token</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"not"</span>
while find(ch," \t\r\n")!=0 do nxtch() end while
<span style="color: #008080;">or</span> <span style="color: #000000;">token</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"!"</span> <span style="color: #008080;">then</span>
end procedure
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">Factor</span><span style="color: #0000FF;">()</span>
procedure get_token()
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">PopFactor</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
skipspaces()
<span style="color: #000000;">PushOp</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"not"</span><span style="color: #0000FF;">)</span>
if find(ch,"()!") then
<span style="color: #008080;">elsif</span> <span style="color: #000000;">token</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"("</span> <span style="color: #008080;">then</span>
token = s[sidx..sidx]
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
nxtch()
<span style="color: #000000;">Expr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
else
<span style="color: #000000;">Match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">")"</span><span style="color: #0000FF;">)</span>
integer tokstart = sidx
<span style="color: #008080;">elsif</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">token</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"and"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"or"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"xor"</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">then</span>
if ch=-1 then token = "eof" return end if
<span style="color: #000000;">PushFactor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">token</span><span style="color: #0000FF;">)</span>
while 1 do
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
nxtch()
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
if ch<'A' then exit end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">else</span>
token = s[tokstart..sidx-1]
<span style="color: #000000;">err</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"syntax error"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure Match(string t)
<span style="color: #008080;">constant</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">operators</span><span style="color: #0000FF;">,</span>
if token!=t then err(t&" expected") end if
<span style="color: #000000;">precedence</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"not"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
get_token()
<span style="color: #0000FF;">{</span><span style="color: #008000;">"and"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">},</span>
end procedure
<span style="color: #0000FF;">{</span><span style="color: #008000;">"xor"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"or"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">}})</span>
procedure PopFactor()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Expr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
object p2 = opstack[$]
<span style="color: #000000;">Factor</span><span style="color: #0000FF;">()</span>
if op="not" then
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
opstack[$] = {0,op,p2}
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">token</span><span style="color: #0000FF;">,</span><span style="color: #000000;">operators</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
opstack = opstack[1..$-1]
<span style="color: #004080;">integer</span> <span style="color: #000000;">thisp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">precedence</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
opstack[$] = {opstack[$],op,p2}
<span style="color: #008080;">if</span> <span style="color: #000000;">thisp</span><span style="color: #0000FF;"><</span><span style="color: #000000;">p</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
op = 0
<span style="color: #000000;">Expr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">thisp</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #000000;">PushOp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">operators</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">])</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
sequence names -- {"false","true",...}
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
sequence flags -- { 0, 1, ,...}
<span style="color: #008080;">function</span> <span style="color: #000000;">evaluate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
procedure PushFactor(string t)
<span style="color: #008080;">if</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
if op!=0 then PopFactor() end if
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">s</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer k = find(t,names)
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
if k=0 then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
names = append(names,t)
<span style="color: #004080;">object</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">lhs</span><span style="color: #0000FF;">,</span><span style="color: #000000;">op</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rhs</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
k = length(names)
<span style="color: #000000;">lhs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">evaluate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lhs</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #000000;">rhs</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">evaluate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rhs</span><span style="color: #0000FF;">)</span>
opstack = append(opstack,k)
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"and"</span> <span style="color: #008080;">then</span>
end procedure
<span style="color: #008080;">return</span> <span style="color: #000000;">lhs</span> <span style="color: #008080;">and</span> <span style="color: #000000;">rhs</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"or"</span> <span style="color: #008080;">then</span>
procedure PushOp(string t)
<span style="color: #008080;">return</span> <span style="color: #000000;">lhs</span> <span style="color: #008080;">or</span> <span style="color: #000000;">rhs</span>
if op!=0 then PopFactor() end if
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"xor"</span> <span style="color: #008080;">then</span>
op = t
<span style="color: #008080;">return</span> <span style="color: #000000;">lhs</span> <span style="color: #008080;">xor</span> <span style="color: #000000;">rhs</span>
end procedure
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"not"</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #008080;">not</span> <span style="color: #000000;">rhs</span>
procedure Factor()
<span style="color: #008080;">else</span>
if token="not"
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span>
or token="!" then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
get_token()
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Factor()
if op!=0 then PopFactor() end if
<span style="color: #008080;">function</span> <span style="color: #000000;">next_comb</span><span style="color: #0000FF;">()</span>
PushOp("not")
<span style="color: #004080;">integer</span> <span style="color: #000000;">fdx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flags</span><span style="color: #0000FF;">)</span>
elsif token="(" then
<span style="color: #008080;">while</span> <span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
get_token()
<span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
Expr(0)
<span style="color: #000000;">fdx</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
Match(")")
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
elsif not find(token,{"and","or","xor"}) then
<span style="color: #008080;">if</span> <span style="color: #000000;">fdx</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- all done</span>
PushFactor(token)
<span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">fdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if ch!=-1 then
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
get_token()
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end if
else
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">expr</span><span style="color: #0000FF;">)</span>
err("syntax error")
<span style="color: #000000;">opstack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
end if
<span style="color: #000000;">op</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
end procedure
<span style="color: #000000;">names</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"false"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"true"</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">expr</span>
constant {operators,
<span style="color: #000000;">sidx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
precedence} = columnize({{"not",6},
<span style="color: #000000;">nxtch</span><span style="color: #0000FF;">()</span>
{"and",5},
<span style="color: #000000;">get_token</span><span style="color: #0000FF;">()</span>
{"xor",4},
<span style="color: #000000;">Expr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
{"or",3}})
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000000;">PopFactor</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">opstack</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">err</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"some error"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
procedure Expr(integer p)
<span style="color: #000000;">flags</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">))</span>
Factor()
<span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- set "true" true</span>
while 1 do
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">..$]),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
integer k = find(token,operators)
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if k=0 then exit end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flags</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (skipping true&false)</span>
integer thisp = precedence[k]
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s%s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flags</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]))})</span>
if thisp<p then exit end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
get_token()
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">evaluate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">opstack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]))})</span>
Expr(thisp)
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">next_comb</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
PushOp(operators[k])
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end while
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
function eval(object s)
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"young and not (ugly or poor)"</span><span style="color: #0000FF;">)</span>
if atom(s) then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (no gets(0) in a browser)</span>
if s>=1 then s = flags[s] end if
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
return s
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"input expression:"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">))</span>
object {lhs,op,rhs} = s
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
lhs = eval(lhs)
<span style="color: #008080;">if</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
rhs = eval(rhs)
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
if op="and" then
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
return lhs and rhs
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
elsif op="or" then
<!--</syntaxhighlight>-->
return lhs or rhs
elsif op="xor" then
return lhs xor rhs
elsif op="not" then
return not rhs
else
?9/0
end if
end function
 
function next_comb()
integer fdx = length(flags)
while flags[fdx]=1 do
flags[fdx] = 0
fdx -= 1
end while
if fdx<=2 then return false end if -- all done
flags[fdx] = 1
return true
end function
 
function fmt(bool b)
return {"0","1"}[b+1] -- for 0/1
-- return {"F","T"}[b+1] -- for F/T
end function
 
procedure test(string expr)
opstack = {}
op = 0
names = {"false","true"}
s = expr
sidx = 0
nxtch()
get_token()
Expr(0)
if op!=0 then PopFactor() end if
if length(opstack)!=1 then err("some error") end if
flags = repeat(0,length(names))
flags[2] = 1 -- set "true" true
printf(1,"%s %s\n",{join(names[3..$]),s})
while 1 do
for i=3 to length(flags) do -- (skipping true&false)
printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))})
end for
printf(1," %s\n",{fmt(eval(opstack[1]))})
if not next_comb() then exit end if
end while
puts(1,"\n")
end procedure
 
test("young and not (ugly or poor)")
while 1 do
puts(1,"input expression:")
string t = trim(gets(0))
puts(1,"\n")
if t="" then exit end if
test(t)
end while</lang>
{{out}}
<pre>
Line 3,738 ⟶ 4,730:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de truthTable (Expr)
(let Vars
(uniq
Line 3,761 ⟶ 4,753:
(space (if (print (val "V")) 6 4)) )
(println (eval Expr))
(find '(("V") (set "V" (not (val "V")))) Vars) ) ) ) )</langsyntaxhighlight>
Test:
 
 
<langsyntaxhighlight PicoLisplang="picolisp">: (truthTable (str "A and (B or C)"))
A B C
NIL NIL NIL NIL
Line 3,807 ⟶ 4,799:
T NIL T T
NIL T T T
T T T NIL</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|Any - tested with release 7.6.4}}
<langsyntaxhighlight lang="prolog">/*
To evaluate the truth table a line of text is inputted and then there are three steps
Let's say the expression is:
Line 3,909 ⟶ 4,901:
e(xor,0,0,0). e(xor,0,1,1). e(xor,1,0,1). e(xor,1,1,0).
e(nand,0,0,1). e(nand,0,1,1). e(nand,1,0,1). e(nand,1,1,0).
e(not, 1, 0). e(not, 0, 1).</langsyntaxhighlight>
{{out}}
<pre>
Line 3,930 ⟶ 4,922:
=={{header|Python}}==
This accepts correctly formatted Python boolean expressions.
<langsyntaxhighlight lang="python">from itertools import product
 
while True:
Line 3,944 ⟶ 4,936:
env = dict(zip(names, values))
print(' '.join(str(v) for v in values), ':', eval(code, env))
</syntaxhighlight>
</lang>
 
;Sample output:
Line 3,990 ⟶ 4,982:
 
Thank you</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ stack ] is args ( --> s )
[ stack ] is results ( --> s )
[ stack ] is function ( --> s )
[ args share times
[ sp
2 /mod iff
[ char t ]
else
[ char f ]
emit ]
drop
say " | " ] is echoargs ( n --> )
[ args share times
[ 2 /mod swap ]
drop ] is preparestack ( n --> b*n )
 
[ results share times
[ sp
iff
[ char t ]
else
[ char f ]
emit ] ] is echoresults ( b*? --> )
[ say "Please input your function, preceded" cr
$ "by the number of arguments and results: " input
trim nextword quackery args put
trim nextword quackery results put
trim build function put
args share bit times
[ cr
i^ echoargs
i^ preparestack
function share do
echoresults ]
cr
args release
results release
function release ] is truthtable ( --> )
</syntaxhighlight>
 
{{out}}
 
Testing in the Quackery shell.
 
<pre>/O> truthtable
...
Please input your function, preceded
by the number of arguments and results: 2 1 or not
 
f f | t
t f | f
f t | f
t t | f
 
Stack empty.
 
/O> truthtable
...
Please input your function, preceded
by the number of arguments and results: 3 1 and or
 
f f f | f
t f f | t
f t f | f
t t f | t
f f t | f
t f t | t
f t t | t
t t t | t
 
Stack empty.
 
/O> truthtable
...
Please input your function, preceded
by the number of arguments and results: 2 2 2dup and unrot xor ( this is a half-adder )
 
f f | f f
t f | t f
f t | t f
t t | f t
 
Stack empty.</pre>
 
=={{header|R}}==
 
<syntaxhighlight lang="r">
<lang r>
truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
Line 4,060 ⟶ 5,141:
## 15 FALSE TRUE TRUE TRUE TRUE
## 16 TRUE TRUE TRUE TRUE FALSE
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 4,066 ⟶ 5,147:
Since the requirement is to read an expression dynamically, <tt>eval</tt> is a natural choice. The following isn't trying to protect against bad inputs when doing that.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 4,095 ⟶ 5,176:
(printf "Enter an expression: ")
(truth-table (read))
</syntaxhighlight>
</lang>
 
Sample run:
Line 4,114 ⟶ 5,195:
(formerly Perl 6)
{{works with|Rakudo|2016.01}}
<syntaxhighlight lang="raku" perl6line>use MONKEY-SEE-NO-EVAL;
 
sub MAIN ($x) {
Line 4,123 ⟶ 5,204:
.join("\t").say for map &fun, flat map { .fmt("\%0{+@n}b").comb».Int».so }, 0 ..^ 2**@n;
say '';
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,178 ⟶ 5,259:
::* &nbsp; '''^''' &nbsp; &nbsp; (caret, &nbsp; circumflex, &nbsp; hat)
Also included is support for two boolean values: '''TRUE''' and '''FALSE''' which are part of boolean expressions.
<langsyntaxhighlight lang="rexx">/*REXX program displays a truth table of variables and an expression. Infix notation */
/*─────────────── is supported with one character propositional constants; variables */
/*─────────────── (propositional constants) that are allowed: A──►Z, a──►z except u.*/
Line 4,413 ⟶ 5,494:
/*f*/ when ? == 'TRUE' then return 1
otherwise return -13
end /*select*/ /* [↑] error, unknown function.*/</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
 
Line 4,514 ⟶ 5,595:
=={{header|Ruby}}==
Uses <code>eval</code>, so blindly trusts the user's input. The core <code>true</code> and <code>false</code> objects understand the methods <code>&</code> (and), <code>|</code> (or), <code>!</code> (not) and <code>^</code> (xor) -- [http://www.ruby-doc.org/core-1.9.2/TrueClass.html]
<langsyntaxhighlight lang="ruby">loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
Line 4,539 ⟶ 5,620:
 
eval (prefix + [body] + suffix).join("\n")
end</langsyntaxhighlight>
 
Example
Line 4,583 ⟶ 5,664:
Extending the set of implemented operators should be almost trivial without any change of the logically more complex parts.
 
<langsyntaxhighlight Rustlang="rust">use std::{
collections::HashMap,
fmt::{Display, Formatter},
Line 5,016 ⟶ 6,097:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,045 ⟶ 6,126:
 
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program truth_table;
exprstr := "" +/ command_line;
if exprstr = "" then
print("Enter a Boolean expression on the command line.");
else
showtable(exprstr);
end if;
 
proc showtable(exprstr);
if (toks := tokenize(exprstr)) = om then return; end if;
if (bexp := parse(toks)) = om then return; end if;
vars := [v : v in getvars(bexp)]; $ fix the variable order
 
$ show table header
tabh := "";
loop for v in vars do
tabh +:= v + " ";
end loop;
print(tabh +:= "| " + exprstr);
print('-' * #tabh);
 
$ show table rows
loop for inst in instantiations(vars) do
loop for v in vars do
putchar(rpad(showbool(inst(v)), #v) + " ");
end loop;
print("| " + showbool(booleval(bexp, inst)));
end loop;
end proc;
 
proc showbool(b); return if b then "1" else "0" end if; end proc;
 
proc instantiations(vars);
insts := [];
loop for i in [0..2**#vars-1] do
inst := {};
loop for v in vars do
inst(v) := i mod 2 /= 0;
i div:= 2;
end loop;
insts with:= inst;
end loop;
return insts;
end proc;
 
proc booleval(tokens, inst);
stack := [];
loop for token in tokens do
case token of
("~"): x frome stack; stack with:= not x;
("&"): y frome stack; x frome stack; stack with:= x and y;
("|"): y frome stack; x frome stack; stack with:= x or y;
("^"): y frome stack; x frome stack; stack with:= x /= y;
("=>"): y frome stack; x frome stack; stack with:= x impl y;
("0"): stack with:= false;
("1"): stack with:= true;
else stack with:= inst(token);
end case;
end loop;
answer frome stack;
return answer;
end proc;
 
proc getvars(tokens);
return {tok : tok in tokens | to_upper(tok(1)) in "ABCDEFGHIJKLMNOPQRSTUVWXYZ_"};
end proc;
 
proc parse(tokens);
ops := {["~", 4], ["&", 3], ["|", 2], ["^", 2], ["=>", 1]};
stack := [];
queue := [];
loop for token in tokens do
if token in domain ops then
loop while stack /= []
and (top := stack(#stack)) /= "("
and ops(top) > ops(token) do
oper frome stack;
queue with:= oper;
end loop;
stack with:= token;
elseif token = "(" then
stack with:= token;
elseif token = ")" then
loop doing
if stack = [] then
print("Missing (.");
return om;
end if;
oper frome stack;
while oper /= "(" do
queue with:= oper;
end loop;
elseif token(1) in "23456789" then
print("Invalid boolean ", token);
return om;
else
queue with:= token;
end if;
end loop;
 
loop while stack /= [] do
oper frome stack;
if oper = "(" then
print("Missing ).");
return om;
end if;
queue with:= oper;
end loop;
return queue;
end proc;
 
proc tokenize(s);
varchars := "abcdefghijklmnopqrstuvwxyz";
varchars +:= to_upper(varchars);
varchars +:= "0123456789_";
 
tokens := [];
 
loop doing span(s, " \t\n"); while s /= "" do
if (tok := any(s, "()&|~^")) /= "" $ brackets/single char operators
or (tok := match(s, "=>")) /= "" $ implies (=>)
or (tok := span(s, "0123456789")) /= "" $ numbers
or (tok := span(s, varchars)) /= "" $ variables
then
tokens with:= tok;
else
print("Parse error at", s);
return om;
end if;
end loop;
return tokens;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>$ setl truth.setl '(human=>mortal) & (socrates=>human) => (socrates=>mortal)'
human mortal socrates | (human=>mortal) & (socrates=>human) => (socrates=>mortal)
---------------------------------------------------------------------------------
0 0 0 | 1
1 0 0 | 1
0 1 0 | 1
1 1 0 | 1
0 0 1 | 1
1 0 1 | 1
0 1 1 | 1
1 1 1 | 1</pre>
 
=={{header|Sidef}}==
{{trans|Ruby}}
A simple solution which accepts arbitrary user-input:
<langsyntaxhighlight lang="ruby">loop {
var expr = Sys.readln("\nBoolean expression (e.g. 'a & b'): ").strip.lc
break if expr.is_empty;
Line 5,071 ⟶ 6,299:
var body = ("say (" + vars.map{|v| v+",'\t'," }.join + " '| ', #{expr})")
eval(prefix + [body] + suffix -> join("\n"))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,088 ⟶ 6,316:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">[:repeat |
expr := Stdin
request:'Enter boolean expression (name variables a,b,c...):'
Line 5,142 ⟶ 6,370:
].
 
allCombinationsDo value:varNames value:#() value:func</langsyntaxhighlight>
{{out}}
<pre>Enter boolean expression (name variables a,b,c...): [[a|b]]:
Line 5,182 ⟶ 6,410:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
puts -nonewline "Enter a boolean expression: "
Line 5,198 ⟶ 6,426:
 
puts [join $vars \t]\tResult
apply [list {} $cmd]</langsyntaxhighlight>
Sample run:
<pre>
Line 5,214 ⟶ 6,442:
 
{{omit from|GUISS}}
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Structure Operator_
Public ReadOnly Symbol As Char
Public ReadOnly Precedence As Integer
Public ReadOnly Arity As Integer
Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean)
 
Public Sub New(symbol As Char, precedence As Integer, f As Func(Of Boolean, Boolean))
Me.New(symbol, precedence, 1, Function(l, r) f(r))
End Sub
 
Public Sub New(symbol As Char, precedence As Integer, f As Func(Of Boolean, Boolean, Boolean))
Me.New(symbol, precedence, 2, f)
End Sub
 
Public Sub New(symbol As Char, precedence As Integer, arity As Integer, fun As Func(Of Boolean, Boolean, Boolean))
Me.Symbol = symbol
Me.Precedence = precedence
Me.Arity = arity
Me.Fun = fun
End Sub
End Structure
 
Public Class OperatorCollection
Implements IEnumerable(Of Operator_)
 
ReadOnly operators As IDictionary(Of Char, Operator_)
 
Public Sub New(operators As IDictionary(Of Char, Operator_))
Me.operators = operators
End Sub
 
Public Sub Add(symbol As Char, precedence As Integer, fun As Func(Of Boolean, Boolean))
operators.Add(symbol, New Operator_(symbol, precedence, fun))
End Sub
Public Sub Add(symbol As Char, precedence As Integer, fun As Func(Of Boolean, Boolean, Boolean))
operators.Add(symbol, New Operator_(symbol, precedence, fun))
End Sub
 
Public Sub Remove(symbol As Char)
operators.Remove(symbol)
End Sub
 
Public Function GetEnumerator() As IEnumerator(Of Operator_) Implements IEnumerable(Of Operator_).GetEnumerator
Return operators.Values.GetEnumerator
End Function
 
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
End Class
 
Structure BitSet
Private ReadOnly bits As Integer
 
Public Sub New(bits As Integer)
Me.bits = bits
End Sub
 
Public Shared Operator +(bs As BitSet, v As Integer) As BitSet
Return New BitSet(bs.bits + v)
End Operator
 
Default Public ReadOnly Property Test(index As Integer) As Boolean
Get
Return (bits And (1 << index)) <> 0
End Get
End Property
End Structure
 
Public Class TruthTable
Enum TokenType
Unknown
WhiteSpace
Constant
Operand
Operator_
LeftParenthesis
RightParenthesis
End Enum
 
ReadOnly falseConstant As Char
ReadOnly trueConstant As Char
ReadOnly operatorDict As New Dictionary(Of Char, Operator_)
 
Public ReadOnly Operators As OperatorCollection
 
Sub New(falseConstant As Char, trueConstant As Char)
Me.falseConstant = falseConstant
Me.trueConstant = trueConstant
Operators = New OperatorCollection(operatorDict)
End Sub
 
Private Function TypeOfToken(c As Char) As TokenType
If Char.IsWhiteSpace(c) Then
Return TokenType.WhiteSpace
End If
If c = "("c Then
Return TokenType.LeftParenthesis
End If
If c = ")"c Then
Return TokenType.RightParenthesis
End If
If c = trueConstant OrElse c = falseConstant Then
Return TokenType.Constant
End If
If operatorDict.ContainsKey(c) Then
Return TokenType.Operator_
End If
If Char.IsLetter(c) Then
Return TokenType.Operand
End If
 
Return TokenType.Unknown
End Function
 
Private Function Precedence(op As Char) As Integer
Dim o As New Operator_
If operatorDict.TryGetValue(op, o) Then
Return o.Precedence
Else
Return Integer.MinValue
End If
End Function
 
Public Function ConvertToPostfix(infix As String) As String
Dim stack As New Stack(Of Char)
Dim postfix As New StringBuilder()
For Each c In infix
Dim type = TypeOfToken(c)
Select Case type
Case TokenType.WhiteSpace
Continue For
Case TokenType.Constant, TokenType.Operand
postfix.Append(c)
Case TokenType.Operator_
Dim precedence_ = Precedence(c)
While stack.Count > 0 AndAlso Precedence(stack.Peek()) > precedence_
postfix.Append(stack.Pop())
End While
stack.Push(c)
Case TokenType.LeftParenthesis
stack.Push(c)
Case TokenType.RightParenthesis
Dim top As Char
While stack.Count > 0
top = stack.Pop()
If top = "("c Then
Exit While
Else
postfix.Append(top)
End If
End While
If top <> "("c Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Case Else
Throw New ArgumentException("Invalid character: " + c)
End Select
Next
While stack.Count > 0
Dim top = stack.Pop()
If top = "("c Then
Throw New ArgumentException("No matching right parenthesis.")
End If
postfix.Append(top)
End While
Return postfix.ToString
End Function
 
Private Function Evaluate(expression As Stack(Of Char), values As BitSet, parameters As IDictionary(Of Char, Integer)) As Boolean
If expression.Count = 0 Then
Throw New ArgumentException("Invalid expression.")
End If
Dim c = expression.Pop()
Dim type = TypeOfToken(c)
While type = TokenType.WhiteSpace
c = expression.Pop()
type = TypeOfToken(c)
End While
Select Case type
Case TokenType.Constant
Return c = trueConstant
Case TokenType.Operand
Return values(parameters(c))
Case TokenType.Operator_
Dim right = Evaluate(expression, values, parameters)
Dim op = operatorDict(c)
If op.Arity = 1 Then
Return op.Fun(right, right)
End If
 
Dim left = Evaluate(expression, values, parameters)
Return op.Fun(left, right)
Case Else
Throw New ArgumentException("Invalid character: " + c)
End Select
 
Return False
End Function
 
Public Iterator Function GetTruthTable(expression As String, Optional isPostfix As Boolean = False) As IEnumerable(Of String)
If String.IsNullOrWhiteSpace(expression) Then
Throw New ArgumentException("Invalid expression.")
End If
REM Maps parameters to an index in BitSet
REM Makes sure they appear in the truth table in the order they first appear in the expression
Dim parameters = expression _
.Where(Function(c) TypeOfToken(c) = TokenType.Operand) _
.Distinct() _
.Reverse() _
.Select(Function(c, i) Tuple.Create(c, i)) _
.ToDictionary(Function(p) p.Item1, Function(p) p.Item2)
 
Dim count = parameters.Count
If count > 32 Then
Throw New ArgumentException("Cannot have more than 32 parameters.")
End If
Dim header = If(count = 0, expression, String.Join(" ", parameters.OrderByDescending(Function(p) p.Value).Select(Function(p) p.Key)) & " " & expression)
If Not isPostfix Then
expression = ConvertToPostfix(expression)
End If
 
Dim values As BitSet
Dim stack As New Stack(Of Char)(expression.Length)
 
Dim loopy = 1 << count
While loopy > 0
For Each token In expression
stack.Push(token)
Next
Dim result = Evaluate(stack, values, parameters)
If Not IsNothing(header) Then
If stack.Count > 0 Then
Throw New ArgumentException("Invalid expression.")
End If
Yield header
header = Nothing
End If
 
Dim line = If(count = 0, "", " ") + If(result, trueConstant, falseConstant)
line = String.Join(" ", Enumerable.Range(0, count).Select(Function(i) If(values(count - i - 1), trueConstant, falseConstant))) + line
Yield line
values += 1
''''''''''''''''''''''''''''
loopy -= 1
End While
End Function
 
Public Sub PrintTruthTable(expression As String, Optional isPostfix As Boolean = False)
Try
For Each line In GetTruthTable(expression, isPostfix)
Console.WriteLine(line)
Next
Catch ex As ArgumentException
Console.WriteLine(expression + " " + ex.Message)
End Try
End Sub
End Class
 
Sub Main()
Dim tt As New TruthTable("F"c, "T"c)
tt.Operators.Add("!"c, 6, Function(r) Not r)
tt.Operators.Add("&"c, 5, Function(l, r) l And r)
tt.Operators.Add("^"c, 4, Function(l, r) l Xor r)
tt.Operators.Add("|"c, 3, Function(l, r) l Or r)
REM add a crazy operator
Dim rng As New Random
tt.Operators.Add("?"c, 6, Function(r) rng.NextDouble() < 0.5)
Dim expressions() = {
"!!!T",
"?T",
"F & x | T",
"F & (x | T",
"F & x | T)",
"a ! (a & a)",
"a | (a * a)",
"a ^ T & (b & !c)"
}
For Each expression In expressions
tt.PrintTruthTable(expression)
Console.WriteLine()
Next
 
REM Define a different language
tt = New TruthTable("0"c, "1"c)
tt.Operators.Add("-"c, 6, Function(r) Not r)
tt.Operators.Add("^"c, 5, Function(l, r) l And r)
tt.Operators.Add("v"c, 3, Function(l, r) l Or r)
tt.Operators.Add(">"c, 2, Function(l, r) Not l Or r)
tt.Operators.Add("="c, 1, Function(l, r) l = r)
expressions = {
"-X v 0 = X ^ 1",
"(H > M) ^ (S > H) > (S > M)"
}
For Each expression In expressions
tt.PrintTruthTable(expression)
Console.WriteLine()
Next
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>!!!T
F
 
?T
T
 
x F & x | T
F T
T T
 
F & (x | T No matching right parenthesis.
 
F & x | T) No matching left parenthesis.
 
a ! (a & a) Invalid expression.
 
a | (a * a) Invalid character: *
 
a b c a ^ T & (b & !c)
F F F F
F F T F
F T F T
F T T F
T F F T
T F T T
T T F F
T T T T
 
X -X v 0 = X ^ 1
0 0
1 0
 
H M S (H > M) ^ (S > H) > (S > M)
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-seq}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "./dynamic" for Struct
import "./ioutil" for Input
import "./seq" for Stack
import "./str" for Str
 
var Variable = Struct.create("Variable", ["name", "value"])
 
// use integer constants as bools don't support bitwise operators
var FALSE = 0
var TRUE = 1
 
var expr = ""
var variables = []
 
var isOperator = Fn.new { |op| "&|!^".contains(op) }
 
var isVariable = Fn.new { |s| variables.map { |v| v.name }.contains(s) }
 
var evalExpression = Fn.new {
var stack = Stack.new()
for (e in expr) {
var v
if (e == "T") {
v = TRUE
} else if (e == "F") {
v = FALSE
} else if (isVariable.call(e)) {
var vs = variables.where { |v| v.name == e }.toList
if (vs.count != 1) Fiber.abort("Can only be one variable with name %(e).")
v = vs[0].value
} else if (e == "&") {
v = stack.pop() & stack.pop()
} else if (e == "|") {
v = stack.pop() | stack.pop()
} else if (e == "!") {
v = (stack.pop() == TRUE) ? FALSE : TRUE
} else if (e == "^") {
v = stack.pop() ^ stack.pop()
} else {
Fiber.abort("Non-conformant character %(e) in expression")
}
stack.push(v)
}
if (stack.count != 1) Fiber.abort("Something went wrong!")
return stack.peek()
}
 
var setVariables // recursive
setVariables = Fn.new { |pos|
var vc = variables.count
if (pos > vc) Fiber.abort("Argument cannot exceed %(vc).")
if (pos == vc) {
var vs = variables.map { |v| (v.value == TRUE) ? "T" : "F" }.toList
var es = (evalExpression.call() == TRUE) ? "T" : "F"
System.print("%(vs.join(" ")) %(es)")
return
}
variables[pos].value = FALSE
setVariables.call(pos + 1)
variables[pos].value = TRUE
setVariables.call(pos + 1)
}
 
System.print("Accepts single-character variables (except for 'T' and 'F',")
System.print("which specify explicit true or false values), postfix, with")
System.print("&|!^ for and, or, not, xor, respectively; optionally")
System.print("seperated by spaces or tabs. Just enter nothing to quit.")
 
while (true) {
expr = Input.text("\nBoolean expression: ")
if (expr == "") return
expr = Str.upper(expr).replace(" ", "").replace("\t", "")
variables.clear()
for (e in expr) {
if (!isOperator.call(e) && !"TF".contains(e) && !isVariable.call(e)) {
variables.add(Variable.new(e, FALSE))
}
}
if (variables.isEmpty) return
var vs = variables.map { |v| v.name }.join(" ")
System.print("\n%(vs) %(expr)")
var h = vs.count + expr.count + 2
System.print("=" * h)
setVariables.call(0)
}</syntaxhighlight>
 
{{out}}
Sample session:
<pre>
Accepts single-character variables (except for 'T' and 'F',
which specify explicit true or false values), postfix, with
&|!^ for and, or, not, xor, respectively; optionally
seperated by spaces or tabs. Just enter nothing to quit.
 
Boolean expression: A B ^
 
A B AB^
=========
F F F
F T T
T F T
T T F
 
Boolean expression: A B C ^ |
 
A B C ABC^|
==============
F F F F
F F T T
F T F T
F T T F
T F F T
T F T T
T T F T
T T T T
 
Boolean expression: A B C D ^ ^ ^
 
A B C D ABCD^^^
===================
F F F F F
F F F T T
F F T F T
F F T T F
F T F F T
F T F T F
F T T F F
F T T T T
T F F F T
T F F T F
T F T F F
T F T T T
T T F F F
T T F T T
T T T F T
T T T T F
 
Boolean expression:
</pre>
 
=={{header|XBasic}}==
{{trans|C}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "truthtables"
VERSION "0.001"
Line 5,437 ⟶ 7,160:
END FUNCTION
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
9,482

edits