Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog query exercise

Tags:

prolog

Here are my given clauses

beats(rock, scissors).
beats(scissors, paper).
beats(paper, rock).

better(battleaxe, scissors).
better(lightsabre, battleaxe).
better(boulder, rock).
better(adamantium, boulder).
better(palisade, paper).
better(nanomesh, palisade).

uses(wolverine, adamantium).
uses(vader, lightsabre).
uses(conan, battleaxe).
uses(richard, rock).

win(X,Y) :- beats(X,Y).
win(X,Y) :- better(X,Y).
win(X,Y) :- better(X,'underscore here'), beats('underscore here',Y). 
win(X,Y) :- better(X,A), better(Y,B), win(A,B).
win(X,Y) :- uses(X,A), uses(Y,B), !, win(A,B).

play(X,Y,X) :- win(X,Y).
play(X,Y,Y) :- win(Y,X).

the question is asking what result i would get from

?- win(X, nanomesh).

the answer is supposed to be X = lightsabre. However I really do not get why.

Could anyone explain this please?

like image 437
Haroldy Avatar asked Dec 31 '25 08:12

Haroldy


1 Answers

There are several ways how you can try to understand this particular query. One way, is to add goals false into your program, such that you still get the same answer. By adding false the program is specialized. If it then still gets the same answer, we know that a responsible part is in the visible area. The strike-through parts indicate clauses you now can ignore completely.

beats(rock, scissors) :- false.
beats(scissors, paper).
beats(paper, rock) :- false.

better(battleaxe, scissors).
better(lightsabre, battleaxe).
better(boulder, rock) :- false.
better(adamantium, boulder) :- false.
better(palisade, paper).
better(nanomesh, palisade).

win(X,Y) :- beats(X,Y).
win(X,Y) :- false, better(X,Y).
win(X,Y) :- false, better(X,'underscore here'), beats('underscore here',Y).
win(X,Y) :- better(X,A), better(Y,B), win(A,B).

?- win(lightsabre, nanomesh).

So you have two chains:

nanomesh   -> palisade  -> paper` 
lightsabre -> battleaxe -> scissors

And finally scissors beat paper.

Not sure I agree with this kind of reasoning, though.

like image 89
false Avatar answered Jan 02 '26 11:01

false