A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.



Task

 Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function.
 (One can assume that the user input is correct).
 Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. 
 Either reverse-polish or infix notation expressions are allowed.


Related tasks

   Boolean values
   Ternary logic


See also

   Wolfram MathWorld entry on truth tables.
   some "truth table" examples from Google.


/* Maxima already has the following logical operators
          =, # (not equal), not, and, or
define some more and set 'binding power' (operator
precedence) for them
*/
infix("xor", 60)$
"xor"(A,B):= (A or B) and not(A and B)$
 
infix("=>", 59)$
"=>"(A,B):= not A or B$
 
/*
Substitute variables `r' in `e' with values taken from list `l' where
`e' is expression, `r' is a list of independent variables, `l' is a
list of the values
lsubst( '(A + B), ['A, 'B], [1, 2]);
1 + 2;
*/
lsubst(e, r, l):= ev(e, maplist( lambda([x, y], x=y), r, l), 'simp)$
 
/*
"Cartesian power" `n' of list `b'. Returns a list of lists of the form
[<x_1>, ..., <x_n>], were <x_1>, .. <x_n> are elements of list `b'
cartesian_power([true, false], 2);
[[true, true], [true, false], [false, true], [false, false]];
cartesian_power([true, false], 3);
[[true, true, true], [true, true, false], [true, false, true], 
[true, false, false], [false, true, true], [false, true, false], 
[false, false, true], [false, false, false]];
*/
cartesian_power(b, n) := block(
    [aux_lst: makelist(setify(b), n)],
    listify(apply(cartesian_product, aux_lst))
    )$
 
gen_table(expr):= block(
  [var_lst: listofvars(expr), st_lst, res_lst, m],
  st_lst: cartesian_power([true, false], length(var_lst)),
  res_lst: create_list(lsubst(expr, var_lst, val_lst), val_lst, st_lst),
  m      : apply('matrix, cons(var_lst, st_lst)),
  addcol(m, cons(expr, res_lst))
  );
 
/* examples */
gen_table('(not A));
gen_table('(A xor B));
gen_table('(Jim and (Spock xor Bones) or Scotty));
gen_table('(A => (B and A)));
gen_table('(V xor (B xor (K xor D ) )));