Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about printing logic tables with Mathematica

Background: See also: http://mathworld.wolfram.com/TruthTable.html

Mathematica supplied the following function.

 TruthTable[op_, n_] := 
  Module[{l = 
     Flatten[Outer[List, Sequence @@ Table[{True, False}, {n}]], 
      n - 1], a = Array[A, n]}, 
   DisplayForm[
    GridBox[Prepend[Append[#, op @@ #] & /@ l, Append[a, op @@ a]], 
     RowLines -> True, ColumnLines -> True]]]

I printed a table of nand as follows:

 TruthTable[Not[And[#1, #2]] &, 2]

 A[1]   A[2]    !(A[1]&&A[2])
 True   True    False
 True   False   True
 False  True    True
 False  False   True

which is as expected, except for the heading, I would like to use P, Q or A, B as variables.

  • Question: I don't quite understand the use of A in the code. Please comment. ( Perhaps I used the function incorrect? )
like image 808
nilo de roock Avatar asked Sep 10 '11 09:09

nilo de roock


1 Answers

The supplied code does not allow you to choose the symbol or list of symbols for the variables that are put in the logic operation. It instead just constructs a list of variables of the form {A[1],...,A[n]}.

A minimal modification of the code to allow for a user supplied list of variables (and some basic argument checking) is something like

TruthTable[op_, n_Integer?Positive, symbs_List] := Module[{
   l = Flatten[Outer[List, Sequence @@ Table[{True, False}, {n}]], n - 1]}, 
  DisplayForm[GridBox[Prepend[Append[#, op @@ #] & /@ l, 
     Append[symbs, op @@ symbs]], RowLines -> True, 
    ColumnLines -> True]]] /; Length[symbs] == n

TruthTable[op_, n_Integer?Positive, symb_String: "A"] := 
 TruthTable[op, n, Array[Symbol[symb], n]]

The first definition will print the truth table for any given list of variables (can be any expression, but simple symbols or strings look the most sensible). The second definition works exactly like the original code you supplied if given two arguments, the optional third argument is the string from which to construct the symbol used in the truth table.

Then the nand truth table can be printed as

TruthTable[Not[And[#1, #2]] &, 2, {P, Q}]

nand

It looks slightly better in TraditionalForm

TruthTable[Not[And[#1, #2]] &, 2, {P, Q}] // TraditionalForm

nand v2

Or even neater if you use the built-in Nand operator (which is just a pretty form of Not[And[##]]&)

TruthTable[Nand, 3, {P, Q, R}] // TraditionalForm

nand v3


On reflection, the integer argument n in the TruthTable function might be a little redundant if you're supplying an explicit list of variables. I leave it as an exercise to the reader to modify the function so that it works without it... :)

like image 102
Simon Avatar answered Oct 25 '22 17:10

Simon