Using Write in ProLog

27 views

Mr Axolotl

Jun 7, 2017, 1:10:58 AM6/7/17
to SWI-Prolog
Hey,
Im new to ProLog and was wondering about how to use Variables in a write command so I could have "The X ate the Y" when the eat command was used no matter what 2 animals where where. In my code I have "eat(A,C):-eat(A,B),eat(B,C)." which allows, for example a lion to eat a fly or a dog to eat a bird. I had a write command after like so:

eat(lion,dog):-
write('The lion ate the dog').

But I cant do this and make it work for a lion eating a spider so I tried the following but it still did not work and im not sure how to do it.

Here is the code:

eat(lion,dog).
eat(dog,cat).
eat(cat,bird).
eat(bird,spider).
eat(spider,fly).

eat(A,C):-eat(A,B),eat(B,C).

eat(X,Y):-
write(X), write(' ate the '), write(Y).

Thanks for any help.

Feliks Kluzniak

Jun 7, 2017, 7:58:28 AM6/7/17
to Mr Axolotl, SWI-Prolog
Hej,

Your little program actually works, upto a point.  Are you aware that you should press ‘;’ after each answer?

The problem is that once you get all the answers you will fall into infinite recursion.  You can sidestep that by renaming the recursive predicate.

So, for example:

30 ~/tmp/prolog> cat eats.pl
eat(lion, dog).
eat(dog, cat).
eat(cat, bird).
eat(bird, spider).
eat(spider, fly).

eats(A, B) :-eat(A, B).
eats(A, C) :-eat(A, B), eats(B, C).

eats_what(X) :-
eats(X, Y),
write(X), write(' ate the '), write(Y), nl, fail.
eats_what(_) :-
write("That is all, folks!").
31 ~/tmp/prolog> swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 7.4.2)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.

For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- [eats].
true.

?- eats_what(lion).
lion ate the dog
lion ate the cat
lion ate the bird
lion ate the spider
lion ate the fly
That is all, folks!
true.

?-

Hope this helps a little. :-)

— Feliks

--
You received this message because you are subscribed to the Google Groups "SWI-Prolog" group.
To unsubscribe from this group and stop receiving emails from it, send an email to swi-prolog+...@googlegroups.com.

Mr Axolotl

Jun 7, 2017, 7:35:58 PM6/7/17
to SWI-Prolog, tuer...@gmail.com
Hey Feliks,

Thanks for your help but I don't think I understood how to use Variables properly. My aim is to be able to write "eat(lion,spider)." and it respond with "The Lion ate the Spider". Except I need it to work no matter what two animals are in the fact. after I get that working I was going to add an "else statement" that says "The X cant eat the Y" but X and Y being whatever animal again like the top. When I asked the first time I thought I could write eat(lion, spider). and I would change the X and the Y in the fact:
"eat(X,Y):-
write(X), write(' ate the '), write(Y)."
but I understand now that it is not how the variables work and when you type them In like "eat(X,Y). I just replaces them with random animals from the facts set above.

I hope I have done a better job at explaining,
Thanks