Truth table: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: made js compatible)
m (syntax highlighting fixup automation)
Line 21:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">T Symbol
String id
Int lbp
Line 159:
print(v.value, end' ‘ ’)
print(‘: ’p.eval())
print()</langsyntaxhighlight>
 
{{out}}
Line 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 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 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.
<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 702:
DO
print truth table( expr )
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 760:
rules (unlike normal APL, which evaluates right-to-left).
 
<langsyntaxhighlight APLlang="apl">truth←{
op←⍉↑'~∧∨≠→('(4 3 2 2 1 0)
order←⍬⍬{
Line 804:
hdr←hdr,(' ',⍵,' '),[0.5]'─'
hdr⍪(,∘' '⍣(⊃⊃-/1↓¨⍴¨hdr tab))tab
}</langsyntaxhighlight>
 
{{out}}
Line 850:
=={{header|BASIC}}==
 
<langsyntaxhighlight lang="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 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</langsyntaxhighlight>
 
{{out}}
Line 987:
=={{header|C}}==
{{trans|D}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Line 1,179:
}
return 0;
}</langsyntaxhighlight>
 
{{output}}
Line 1,236:
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <stack>
#include <string>
Line 1,370:
 
return 0;
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 1,671:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,718:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure"> (ns clojure-sandbox.truthtables
(:require [clojure.string :as s]
[clojure.pprint :as pprint]))
Line 1,817:
 
(truth-table "! a | b") ;; interpreted as ! (a | b)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,830:
=={{header|Cowgol}}==
 
<langsyntaxhighlight lang="cowgol"># Truth table generator in Cowgol
# -
# This program will generate a truth table for the Boolean expression
Line 2,170:
# next configuration
vars := vars + 1;
end loop; </langsyntaxhighlight>
 
{{out}}
Line 2,224:
=={{header|D}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.array, std.algorithm, std.typecons;
 
struct Var {
Line 2,312:
writefln("%-(%s %) %s", .vars.map!(v => v.name), .expr);
setVariables(0);
}</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="dejavu">print-line lst end:
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</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="factor">USING: arrays combinators eval formatting io kernel listener
math.combinatorics prettyprint qw sequences splitting
vocabs.parser ;
Line 2,480:
add-col print-table drop ;
MAIN: main</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,669:
return false, errors.New(fmt.Sprintf("%v unsupported", i))
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,706:
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,739:
colWidth = max 6 $ maximum $ map length (head tbl)
main = forever $ getLine >>= putStrLn . truthTable</langsyntaxhighlight>
 
{{Out}}
Line 2,766:
 
Translation from infix notation to RPN using Parsec:
<langsyntaxhighlight lang="haskell">{-# LANGUAGE FlexibleContexts #-}
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</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight lang="haskell">λ> putStr $ truthTable $ toRPN "(Human => Mortal) & (Socratus => Human) => (Socratus => Mortal)"
 
Human Mortal Socratus result
Line 2,791:
False True False True
False False True True
False False False True </langsyntaxhighlight>
 
=={{header|J}}==
Line 2,797:
Implementation:
 
<langsyntaxhighlight lang="j">truthTable=:3 :0
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
)</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,809:
Example use:
 
<langsyntaxhighlight lang="j"> truthTable '-.b'
b -.b
0 1
Line 2,840:
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,962:
return stack.pop();
}
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="javascript"><!DOCTYPE html><html><head><title>Truth table</title><script>
var elem,expr,vars;
function isboolop(chr){return "&|!^".indexOf(chr)!=-1;}
Line 3,056:
return stack[0];
}
</script></head><body onload="printtruthtable()"></body></html></langsyntaxhighlight>
{{Out|Output in browser window after entering "AB^"}}
<pre>A B AB^
Line 3,076:
=={{header|Julia}}==
'''Module''':
<langsyntaxhighlight lang="julia">module TruthTable
 
using Printf
Line 3,118:
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 3,166:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
import java.util.Stack
Line 3,239:
setVariables(0)
}
}</langsyntaxhighlight>
 
{{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">
<lang lb>
print
print " TRUTH TABLES"
Line 3,393:
end if
end function
</syntaxhighlight>
</lang>
<pre>
Too_High and Fuel_Out
Line 3,417:
 
=={{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,428:
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,451:
 
=={{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,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 ) )));</langsyntaxhighlight>
 
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>
</lang>
 
=={{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.
 
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, sugar
 
# List of possible variables names.
Line 3,635:
let h = vs.len + expr.formula.len + 2
echo repeat('=', h)
expr.setVariables(0)</langsyntaxhighlight>
 
{{out}}
Line 3,693:
 
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,715:
};
truthTable("x+y") \\ OR
truthTable("x*y") \\ AND</langsyntaxhighlight>
{{out}}
<pre>000
Line 3,730:
{{trans|C}}
{{works with|Free Pascal}}
<syntaxhighlight lang="pascal">
<lang Pascal>
program TruthTables;
const
Line 3,965:
end;
end.
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
sub truth_table {
Line 4,041:
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 4,069:
=={{header|Phix}}==
Expression parsing and evaluation similar to that in the Arithmetic evaluation task.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,273:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de truthTable (Expr)
(let Vars
(uniq
Line 4,296:
(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 4,342:
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 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).</langsyntaxhighlight>
{{out}}
<pre>
Line 4,465:
=={{header|Python}}==
This accepts correctly formatted Python boolean expressions.
<langsyntaxhighlight lang="python">from itertools import product
 
while True:
Line 4,479:
env = dict(zip(names, values))
print(' '.join(str(v) for v in values), ':', eval(code, env))
</syntaxhighlight>
</lang>
 
;Sample output:
Line 4,528:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is args ( --> s )
[ stack ] is results ( --> s )
[ stack ] is function ( --> s )
Line 4,569:
results release
function release ] is truthtable ( --> )
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,617:
=={{header|R}}==
 
<syntaxhighlight lang="r">
<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>
</lang>
 
=={{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>
#lang racket
 
Line 4,719:
(printf "Enter an expression: ")
(truth-table (read))
</syntaxhighlight>
</lang>
 
Sample run:
Line 4,738:
(formerly Perl 6)
{{works with|Rakudo|2016.01}}
<syntaxhighlight lang="raku" perl6line>use MONKEY-SEE-NO-EVAL;
 
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 '';
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,802:
::* &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 5,037:
/*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 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]
<langsyntaxhighlight lang="ruby">loop do
print "\ninput a boolean expression (e.g. 'a & b'): "
expr = gets.strip.downcase
Line 5,163:
 
eval (prefix + [body] + suffix).join("\n")
end</langsyntaxhighlight>
 
Example
Line 5,207:
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,640:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,673:
{{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,695:
var body = ("say (" + vars.map{|v| v+",'\t'," }.join + " '| ', #{expr})")
eval(prefix + [body] + suffix -> join("\n"))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,712:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">[:repeat |
expr := Stdin
request:'Enter boolean expression (name variables a,b,c...):'
Line 5,766:
].
 
allCombinationsDo value:varNames value:#() value:func</langsyntaxhighlight>
{{out}}
<pre>Enter boolean expression (name variables a,b,c...): [[a|b]]:
Line 5,806:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
puts -nonewline "Enter a boolean expression: "
Line 5,822:
 
puts [join $vars \t]\tResult
apply [list {} $cmd]</langsyntaxhighlight>
Sample run:
<pre>
Line 5,841:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Line 6,144:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>!!!T
Line 6,194:
{{libheader|Wren-seq}}
{{libheader|Wren-str}}
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Struct
import "/ioutil" for Input
import "/seq" for Stack
Line 6,278:
System.print("=" * h)
setVariables.call(0)
}</langsyntaxhighlight>
 
{{out}}
Line 6,337:
{{trans|C}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "truthtables"
VERSION "0.001"
Line 6,556:
END FUNCTION
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
10,327

edits