Reputation: 1141
I have the following code I've been working on for an expert system:
in(switzterland, 'prairie dog').
in(austria,'wild dog').
in(czechia, 'giant panda').
in(america, 'red kangaroo').
linked(switzterland, austria).
linked(austria, czechia).
linked(czechia, america).
tour(X, Y) :-
linked(X, Y),
in(X, Z), habitant(Z, I),
format('~s~t~14|~s~t~31|', ['Animal Name: ',Z]),
format('~s~t~8|~s~t~23|', ['Habitant: ',I]),
format('~s~t~8|~s~t~25|', ['Region: ',X]), nl,
in(Y, U), habitant(U, T),
format('~s~t~14|~s~t~31|', ['Animal Name: ',U]),
format('~s~t~8|~s~t~23|', ['Habitant: ',T]),
format('~s~t~8|~s~t~25|', ['Region: ',Y]), nl,!.
tour(X, Y) :-
format('~s~t~14|~s~s~s\n~s', ['Dear customer, your tour is from: ',X,
' to ', Y,'Through your visit, you\'ll be able to see the following animals, please enjoy.']),nl,nl,
in(X, Z), habitant(Z, I),
format('~s~t~14|~s~t~31|', ['Animal Name: ',Z]),
format('~s~t~8|~s~t~23|', ['Habitant: ',I]),
format('~s~t~8|~s~t~25|', ['Region: ',X]), nl,
linked(X, F), tour(F, Y).
output is :
Dear customer, your tour is from: switzterland to america
Through your visit, you'll be able to see the following animals, please enjoy.
Animal Name: prairie dog Habitant: grasslands Region: switzterland
Dear customer, your tour is from: austria to america
Through your visit, you'll be able to see the following animals, please enjoy.
Animal Name: wild dog Habitant: grassland Region: austria
Animal Name: giant panda Habitant: open forest Region: czechia
Animal Name: red kangaroo Habitant: woodlands Region: america
You can see that 'Dear customer ....' is being repeated twice, or every time there's a recursive call to the second tour, it will print again. I only wants that to be printed one time.
Upvotes: 0
Views: 235
Reputation: 18663
You need two predicates, the first one (e.g. tour/2
) printing the 'Dear customer ....' message and calling the second predicate (e.g. find_tour/2
) that computes the tour(s). For example:
tour(X, Y) :-
format('~s~t~14|~s~s~s\n~s', ['Dear customer, your tour is from: ',X,
' to ', Y,'Through your visit, you\'ll be able to see the following animals, please enjoy.']),nl,nl,
find_tour(X, Y).
find_tour(X, Y) :-
linked(X, Y),
in(X, Z), habitant(Z, I),
format('~s~t~14|~s~t~31|', ['Animal Name: ',Z]),
format('~s~t~8|~s~t~23|', ['Habitant: ',I]),
format('~s~t~8|~s~t~25|', ['Region: ',X]), nl,
in(Y, U), habitant(U, T),
format('~s~t~14|~s~t~31|', ['Animal Name: ',U]),
format('~s~t~8|~s~t~23|', ['Habitant: ',T]),
format('~s~t~8|~s~t~25|', ['Region: ',Y]), nl,!.
find_tour(X, Y) :-
in(X, Z), habitant(Z, I),
format('~s~t~14|~s~t~31|', ['Animal Name: ',Z]),
format('~s~t~8|~s~t~23|', ['Habitant: ',I]),
format('~s~t~8|~s~t~25|', ['Region: ',X]), nl,
linked(X, F),
find_tour(F, Y).
Upvotes: 1