Reputation: 237
I have this piece of code which suggests for a certain animal which other animals can coexist to it under those circumstances:
suggest(X) :- bigAnimal(X),bigAnimal(Y),coexist(X,Y),write(Y),nl,fail.
This loops until fail.My issue is that it prints out also the variable X
How can I exclude it from the output, thx in adcavance.
Upvotes: 1
Views: 975
Reputation: 10102
In your program you are mixing querying via the toplevel shell and performing side-effects with write/1
. In this manner you will most probably miss a lot of what Prolog can offer you.
Instead, stick to pure side-effect free relations and let all writing be done by the toplevel.
Thus, instead of suggest/1
, consider a new relation, say biganimal_compatiblewith/2
.
biganimal_compatiblewith(X,Y) :-
bigAnimal(X),
bigAnimal(Y),
coexist(X,Y),
dif(X,Y). % maybe
?- biganimal_compatiblewith(X,Y).
X = melan, Y = narty
; X = melman, Y = nelman
; ... .
Now, both X
and Y
are printed on the toplevel. Think how useful this relation is compared to the original suggest/1
. You can ask for one or the other, or you even can ask
?- biganimal_compatiblewith(X,X).
You can also reuse this relation, building more complex ones:
?- biganimal_compatiblewith(X,Y), burgervore(Y).
That is the essence of Prolog relations. You can spare out side effects for quite some time.
For another example how to avoid unnecessary side effects: What are the pros and cons of using manual list iteration vs recursion through fail
Upvotes: 3
Reputation: 18663
suggest(X) :-
bigAnimal(X), bigAnimal(Y), X \== Y, coexist(X,Y), write(Y), nl, fail.
Upvotes: 1
Reputation: 1564
When I have this piece of code:
bigAnimal(elephantas).
bigAnimal(kamilopardali).
coexist(elephantas,kamilopardali).
coexist(kamilopardali,elephantas).
/* coexist has to be symmetric */
suggest(X) :- bigAnimal(X),bigAnimal(Y),coexist(X,Y),write(Y),nl,fail.
The result is as expected.
2 ?- suggest(elephantas).
kamilopardali
false.
4 ?- suggest(kamilopardali).
elephantas
false.
You shouldn't end your code with ;
because that means OR
. When I tried to compile that, I get an error. That's why I have to end my rule with a fullstop (.
)
Upvotes: 1