如何在Prolog中递归调用时只打印一次



我一直在为专家系统编写以下代码:

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~sn~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).

输出为:

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  

你可以看到"亲爱的客户……"正在重复两次,或者每次对第二个巡回进行递归调用时,它都会再次打印。我只想把它印一次。

您需要两个谓词,第一个谓词(例如tour/2(打印"亲爱的客户……"消息并调用计算巡回的第二谓词(例如find_tour/2(。例如:

tour(X, Y) :-
format('~s~t~14|~s~s~sn~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).

最新更新