5

I have to write program that prints a truth table of expressions. So, I wrote the following function:

bool(true).
bool(fail).

tableBody(A,B,E) :-
    bool(A),
    bool(B) ,
    write(A) ,
    write('    '),
    write(B),
    write('    '),
    write(E),nl, fail.

My problem is that E (wich is expression that contains A and B) is not evaluated, but printed as is. For example:

296 ?- table(A,B,and(A,B)).
A    B    expr(A,B)
true    true    and(true, true)
true    fail    and(true, fail)
fail    true    and(fail, true)
fail    fail    and(fail, fail)
false.

I am interested to write the evaluated value of and(true, true) ("and(X,Y)" is a functor I defined earlier) instead of what is currently displayed. I thought about writing an eval functor, but would not it have the same effect? How can I solve this?

I am using SWI-Prolog 5.8. Thank you.

mdb
  • 52,000
  • 11
  • 64
  • 62
Artium
  • 5,147
  • 8
  • 39
  • 60
  • 4
    Curious, I don't understand Prolog, but even using existing programming knowledge/experience, I can't even remotely understand what that code does. Haha. – Nick Bedford Jan 21 '10 at 02:19

2 Answers2

6

Here's one way to do it:

and(A, B) :- A, B.

evaluate(E, true) :- E, !.
evaluate(_, false).

bool(true).
bool(false).

tableBody(A,B,E) :-
  bool(A),
  bool(B),
  write(A),
  write(' \t '),
  write(B),
  write(' \t '),
  evaluate(E, Result),
  write(Result),nl, fail.

Produces:

?- tableBody(A,B,and(A,B)).
true    true    true
true    false   false
false   true    false
false   false   false
false.
Jeff Dallien
  • 4,491
  • 3
  • 22
  • 19
3

As usual, one-liner here

?- forall((member(A,[true,false]),member(B,[true,false]),(A,B->C=true;C=false)),format('~w|~w|~w~n',[A,B,C])).
true|true|true
true|false|false
false|true|false
false|false|false
Volodymyr Gubarkov
  • 2,173
  • 20
  • 20