你如何用 prolog 解决 Russian nesting dolls 问题?

How do you solve Russian nesting dolls question with prolog?

您好,我是 prolog 的新手,正在尝试解决以下问题:

/* 2. Russian nesting dolls:
 * Write a knowledge base using the predicate directlyIn/2 which encodes which doll 
 * is directly contained in which other doll. Then, define a recursive predicate in/2, 
 * that tells us which doll is (directly or indirectly) contained in which other dolls.*/

%% Predicates
directlyIn(katarina, olga).
directlyIn(olga, natasha).
directlyIn(natasha, irina).

%% Rules
in(X, Y) :- directlyIn(X, Y).
in(X,Y) :-
    directlyIn(X,Z),
    in(Z,Y).

为什么下面的查询是returnfalse而不是true

?- in(katerina,natasha).

知道您在描述中告诉我们的内容,您说查询:

?- in(katerina, natasha).

Returnsfalse。但请注意,拼写使 all 有所不同。如果你想看到“katerina”的结果,你应该在你的知识库中包含这个原子,像这样:

directlyIn(katarina, olga).  % All letters make difference here
directlyIn(katerina, olga).  % ?- katerina \== katarina. --> true.  They are different

否则,只需在您的查询中将名称更正为“katarina”,它就会return得到正确答案。以防万一您不想在达到目标后找到更多结果,您可以在递归规则的基本情况下放置一个简单的 cut 运算符(!):

in(X, Y) :- directlyIn(X, Y), !.  % Notice the '!' symbol, it tells the 
                                  % backtracking mechanism NOT to search 
                                  % for more answers to your query.