Search code examples
prologfact

Reversing facts in prolog and display them


If I have the following:

friends(tim,joe).

if i go:

?- friends(X,Y).

I would get:

X=tim
Y=joe

What would I have to print the following with out adding any new facts

X=tim
Y=joe
X=joe
Y=tim

Solution

  • You will have to add a new rule:

    are_friends(X,Y):- friends(X,Y).
    are_friends(X,Y):- friends(Y,X).
    

    Then you ask:

    ?- are_friends(X,Y).
    

    Prolog will answer

    X=tim, Y=joe   _
    

    and it will wait for your further command. If you press ;, then it will print the next solution:

    X=tim, Y=joe   ;
    
    X=joe, Y=tim   _
    

    To just show the results twice - as opposed to producing them in a proper Prolog fashion - we can write

    show_friends :- 
      friends(X,Y),
      write('X='), write(...), write(', Y='), write(...), nl,
      write('X='), write(...), write(', Y='), write(...), nl,
      fail.
    

    but this is really, really, really just faking it. Ughgh. You fill in the blanks.