fork download
  1. % Prolog doesn't know anything at first. "true" and "false" are
  2. % just arbitrary words. We need to use them by way of the operations
  3. % "not", "xor", and "implies", so we'll define those using truth tables:
  4. not(true, false).
  5. not(false, true).
  6.  
  7. xor(false, false, false).
  8. xor(false, true, true).
  9. xor(true, false, true).
  10. xor(true, true, false).
  11.  
  12. implies(false, false, true).
  13. implies(false, true, true).
  14. implies(true, false, false).
  15. implies(true, true, true).
  16.  
  17. % Now, let's write down what we were given...
  18.  
  19. % Statement 1a is true iff (there is a king) implies (there is an ace).
  20. stmt_1a(HasKing, HasAce, Result) :-
  21. implies(HasKing, HasAce, Result).
  22.  
  23. % Statement 1b is true iff (there is not a king) implies (there is an ace).
  24. stmt_1b(HasKing, HasAce, Result) :-
  25. implies(DoesntHaveKing, HasAce, Result),
  26. not(DoesntHaveKing, HasKing).
  27.  
  28. % Statement 1 is true iff (statement 1a) xor (statement 1b) is true.
  29. stmt_1(HasKing, HasAce, Result) :-
  30. xor(Stmt1ATrue, Stmt1BTrue, Result),
  31. stmt_1a(HasKing, HasAce, Stmt1ATrue),
  32. stmt_1b(HasKing, HasAce, Stmt1BTrue).
  33.  
  34. % Statement 2 is true iff there is a king.
  35. stmt_2(HasKing, _HasAce, Result) :-
  36. Result = HasKing.
  37.  
  38. % Finally: we can say we've found a valid assignment (true/false values for
  39. % HasKing and HasAce) if they satisfy both of the given statements.
  40.  
  41. satisfied(HasKing, HasAce) :-
  42. stmt_1(HasKing, HasAce, true),
  43. stmt_2(HasKing, HasAce, true).
  44.  
  45. % Now let's ask Prolog our question: for what values of HasKing and HasAce
  46. % is the statement satisfied?
  47.  
  48. :- satisfied(HasKing, HasAce),
  49. write('Has king: '), write(HasKing), nl,
  50. write('Has ace: '), write(HasAce), nl,
  51. write('--------------'), nl,
  52. % Marking this as a failure causes Prolog to backtrack,
  53. % so if there were multiple solutions, we'd see each of them.
  54. write('No more solutions!'), halt.
Success #stdin #stdout 0s 7468KB
stdin
Standard input is empty
stdout
Has king: true
Has ace: false
--------------
No more solutions!