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

时间:2018-11-24 09:42:52

标签: prolog

我正在为专家系统使用以下代码:

POST _reindex
{
  "source": {
    "index": "creativeindex_src"
  },
  "dest": {
    "index": "creativeindex_dest",
    "pipeline": "my_pipeline"
  }
}

输出为:

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

您会看到“亲爱的客户....”重复了两次,或者每次第二次巡回都有递归调用时,它将再次打印。我只希望将其打印一次。

1 个答案:

答案 0 :(得分:1)

您需要两个谓词,第一个谓词(例如tour/2)会打印“尊敬的客户....”消息,并调用第二个谓词(例如find_tour/2)来计算行程。例如:

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