Truth table: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Phix}}: made js compatible) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 21:
=={{header|11l}}==
<
String id
Int lbp
Line 159:
print(v.value, end' ‘ ’)
print(‘: ’p.eval())
print()</
{{out}}
Line 217:
This program runs under CP/M and takes the Boolean expression on the command line.
<
;;; Supported operators:
;;; ~ (not), & (and), | (or), ^ (xor) and => (implies)
Line 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</
{{out}}
Line 621:
{{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.
<
# 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 702:
DO
print truth table( expr )
OD</
{{out}}
<pre>
Line 760:
rules (unlike normal APL, which evaluates right-to-left).
<
op←⍉↑'~∧∨≠→('(4 3 2 2 1 0)
order←⍬⍬{
Line 804:
hdr←hdr,(' ',⍵,' '),[0.5]'─'
hdr⍪(,∘' '⍣(⊃⊃-/1↓¨⍴¨hdr tab))tab
}</
{{out}}
Line 850:
=={{header|BASIC}}==
<
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 919:
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</
{{out}}
Line 987:
=={{header|C}}==
{{trans|D}}
<
#include <string.h>
#include <stdlib.h>
Line 1,179:
}
return 0;
}</
{{output}}
Line 1,236:
=={{header|C++}}==
{{trans|C}}
<
#include <stack>
#include <string>
Line 1,370:
return 0;
}</
{{out}}
<pre>Accepts single-character variables (except for 'T' and 'F',
Line 1,425:
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.
<
using System.Collections;
using System.Collections.Generic;
Line 1,671:
}
}
}</
{{out}}
<pre>
Line 1,718:
=={{header|Clojure}}==
<
(:require [clojure.string :as s]
[clojure.pprint :as pprint]))
Line 1,817:
(truth-table "! a | b") ;; interpreted as ! (a | b)
</syntaxhighlight>
{{out}}
<pre>
Line 1,830:
=={{header|Cowgol}}==
<
# -
# This program will generate a truth table for the Boolean expression
Line 2,170:
# next configuration
vars := vars + 1;
end loop; </
{{out}}
Line 2,224:
=={{header|D}}==
{{trans|JavaScript}}
<
struct Var {
Line 2,312:
writefln("%-(%s %) %s", .vars.map!(v => v.name), .expr);
setVariables(0);
}</
{{out}}
<pre>Accepts single-character variables (except for 'T' and 'F',
Line 2,359:
=={{header|Déjà Vu}}==
{{incorrect|Déjà Vu|User input is not arbitrary but fixed to the three examples shown}}
<
for v in reversed copy lst:
print\( v chr 9 )
Line 2,384:
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</
{{out}}
<pre>A B A ^ B
Line 2,423:
=={{header|Factor}}==
Postfix is a natural choice. That way, we can use <code>(eval)</code> to to evaluate the expressions without much fuss.
<
math.combinatorics prettyprint qw sequences splitting
vocabs.parser ;
Line 2,480:
add-col print-table drop ;
MAIN: main</
{{out}}
<pre>
Line 2,527:
=={{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.
<
import (
Line 2,669:
return false, errors.New(fmt.Sprintf("%v unsupported", i))
}
</syntaxhighlight>
Output:
<pre>
Line 2,706:
Uses operators "&", "|", "!", "^" (xor), "=>" (implication); all other words are interpreted as variable names.
<
import Data.List (unwords, unlines, nub)
import Data.Maybe (fromJust)
Line 2,739:
colWidth = max 6 $ maximum $ map length (head tbl)
main = forever $ getLine >>= putStrLn . truthTable</
{{Out}}
Line 2,766:
Translation from infix notation to RPN using Parsec:
<
import Text.Parsec
Line 2,778:
many1 alphaNum
op1 s = (\x -> unwords [x, s]) <$ string s
op2 s = (\x y -> unwords [x, y, s]) <$ string s</
{{Out}}
<
Human Mortal Socratus result
Line 2,791:
False True False True
False False True True
False False False True </
=={{header|J}}==
Line 2,797:
Implementation:
<
assert. -. 1 e. 'data expr names table' e.&;: y
names=. ~. (#~ _1 <: nc) ;:expr=. y
Line 2,803:
(names)=. |:data
(' ',;:inv names,<expr),(1+#@>names,<expr)":data,.".expr
)</
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,809:
Example use:
<
b -.b
0 1
Line 2,840:
1 0 1 1
1 1 0 1
1 1 1 1</
=={{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).
<
import java.util.HashMap;
import java.util.Iterator;
Line 2,962:
return stack.pop();
}
}</
{{out}}
Note that the escape character is ^ for Windows
Line 2,997:
=={{header|JavaScript}}==
Actually a HTML document. Save as a .html document and double-click it. You should be fine.
<
var elem,expr,vars;
function isboolop(chr){return "&|!^".indexOf(chr)!=-1;}
Line 3,056:
return stack[0];
}
</script></head><body onload="printtruthtable()"></body></html></
{{Out|Output in browser window after entering "AB^"}}
<pre>A B AB^
Line 3,076:
=={{header|Julia}}==
'''Module''':
<
using Printf
Line 3,118:
end
end # module TruthTable</
'''Main''':
<
TruthTable.@table a | b
TruthTable.@table (a ⊻ b) | (c & a)
TruthTable.@table (a & b) | (c ⊻ d)
</syntaxhighlight>
{{out}}
Line 3,166:
=={{header|Kotlin}}==
{{trans|D}}
<
import java.util.Stack
Line 3,239:
setVariables(0)
}
}</
{{out}}
Line 3,301:
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">
print
print " TRUTH TABLES"
Line 3,393:
end if
end function
</syntaxhighlight>
<pre>
Too_High and Fuel_Out
Line 3,417:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}];
Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]]
Line 3,428:
Join[List[Flatten[{VariableNames[BooleanEquation],BooleanEquation}]],
Flatten[{#/.Rule[x_,y_] -> y,ReplaceAll[ToExpression[BooleanEquation],#]}]&/@TestDataSet]//Grid
]</
Example usage:
<pre>TruthTable["V ~Xor~ (B ~Xor~ (K ~Xor~ D ) )"]
Line 3,451:
=={{header|Maxima}}==
<
=, # (not equal), not, and, or
define some more and set 'binding power' (operator
Line 3,499:
gen_table('(Jim and (Spock xor Bones) or Scotty));
gen_table('(A => (B and A)));
gen_table('(V xor (B xor (K xor D ) )));</
OUtput of the last example:
<syntaxhighlight lang="text">
[ V B K D V xor (B xor (K xor D)) ]
[ ]
Line 3,536:
[ ]
[ false false false false false ]
</syntaxhighlight>
=={{header|Nim}}==
Line 3,542:
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.
<
# List of possible variables names.
Line 3,635:
let h = vs.len + expr.formula.len + 2
echo repeat('=', h)
expr.setVariables(0)</
{{out}}
Line 3,693:
It would be easy to modify the program to take <code>+</code> for XOR instead.
<
my(v=List(),x);
while(type(P)=="t_POL",
Line 3,715:
};
truthTable("x+y") \\ OR
truthTable("x*y") \\ AND</
{{out}}
<pre>000
Line 3,730:
{{trans|C}}
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
program TruthTables;
const
Line 3,965:
end;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 4,021:
=={{header|Perl}}==
Note: can't process stuff like "X xor Y"; "xor" would be treated as a variable name here.
<
sub truth_table {
Line 4,041:
truth_table 'A ^ A_1';
truth_table 'foo & bar | baz';
truth_table 'Jim & (Spock ^ Bones) | Scotty';</
A A_1 A ^ A_1
----------------------------------------
Line 4,069:
=={{header|Phix}}==
Expression parsing and evaluation similar to that in the Arithmetic evaluation task.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 4,256:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
{{out}}
<pre>
Line 4,273:
=={{header|PicoLisp}}==
<
(let Vars
(uniq
Line 4,296:
(space (if (print (val "V")) 6 4)) )
(println (eval Expr))
(find '(("V") (set "V" (not (val "V")))) Vars) ) ) ) )</
Test:
<
A B C
NIL NIL NIL NIL
Line 4,342:
T NIL T T
NIL T T T
T T T NIL</
=={{header|Prolog}}==
{{works with|SWI-Prolog|Any - tested with release 7.6.4}}
<
To evaluate the truth table a line of text is inputted and then there are three steps
Let's say the expression is:
Line 4,444:
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).</
{{out}}
<pre>
Line 4,465:
=={{header|Python}}==
This accepts correctly formatted Python boolean expressions.
<
while True:
Line 4,479:
env = dict(zip(names, values))
print(' '.join(str(v) for v in values), ':', eval(code, env))
</syntaxhighlight>
;Sample output:
Line 4,528:
=={{header|Quackery}}==
<
[ stack ] is results ( --> s )
[ stack ] is function ( --> s )
Line 4,569:
results release
function release ] is truthtable ( --> )
</syntaxhighlight>
{{out}}
Line 4,617:
=={{header|R}}==
<syntaxhighlight lang="r">
truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
Line 4,684:
## 15 FALSE TRUE TRUE TRUE TRUE
## 16 TRUE TRUE TRUE TRUE FALSE
</syntaxhighlight>
=={{header|Racket}}==
Line 4,690:
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
Line 4,719:
(printf "Enter an expression: ")
(truth-table (read))
</syntaxhighlight>
Sample run:
Line 4,738:
(formerly Perl 6)
{{works with|Rakudo|2016.01}}
<syntaxhighlight lang="raku"
sub MAIN ($x) {
Line 4,747:
.join("\t").say for map &fun, flat map { .fmt("\%0{+@n}b").comb».Int».so }, 0 ..^ 2**@n;
say '';
}</
{{out}}
<pre>
Line 4,802:
::* '''^''' (caret, circumflex, hat)
Also included is support for two boolean values: '''TRUE''' and '''FALSE''' which are part of boolean expressions.
<
/*─────────────── is supported with one character propositional constants; variables */
/*─────────────── (propositional constants) that are allowed: A──►Z, a──►z except u.*/
Line 5,037:
/*f*/ when ? == 'TRUE' then return 1
otherwise return -13
end /*select*/ /* [↑] error, unknown function.*/</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]].
Line 5,138:
=={{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]
<
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
Line 5,163:
eval (prefix + [body] + suffix).join("\n")
end</
Example
Line 5,207:
Extending the set of implemented operators should be almost trivial without any change of the logically more complex parts.
<
collections::HashMap,
fmt::{Display, Formatter},
Line 5,640:
}
}
}</
{{out}}
Line 5,673:
{{trans|Ruby}}
A simple solution which accepts arbitrary user-input:
<
var expr = Sys.readln("\nBoolean expression (e.g. 'a & b'): ").strip.lc
break if expr.is_empty;
Line 5,695:
var body = ("say (" + vars.map{|v| v+",'\t'," }.join + " '| ', #{expr})")
eval(prefix + [body] + suffix -> join("\n"))
}</
{{out}}
<pre>
Line 5,712:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<
expr := Stdin
request:'Enter boolean expression (name variables a,b,c...):'
Line 5,766:
].
allCombinationsDo value:varNames value:#() value:func</
{{out}}
<pre>Enter boolean expression (name variables a,b,c...): [[a|b]]:
Line 5,806:
=={{header|Tcl}}==
<
puts -nonewline "Enter a boolean expression: "
Line 5,822:
puts [join $vars \t]\tResult
apply [list {} $cmd]</
Sample run:
<pre>
Line 5,841:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 6,144:
End Sub
End Module</
{{out}}
<pre>!!!T
Line 6,194:
{{libheader|Wren-seq}}
{{libheader|Wren-str}}
<
import "/ioutil" for Input
import "/seq" for Stack
Line 6,278:
System.print("=" * h)
setVariables.call(0)
}</
{{out}}
Line 6,337:
{{trans|C}}
{{works with|Windows XBasic}}
<
PROGRAM "truthtables"
VERSION "0.001"
Line 6,556:
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
|