2011-06-12 27 views
0

我有一个功能从书:序言-SWI:过程,它删除一个occurence

% Signature: select (X,HasXs,OneLessXs)/3 
% purpose: The list OneLessXs is the result of removing 
one occurrence of X from the list HasXs. 
select(X,[X|Xs],Xs). *rule number 1* 
select(X,[Y|Ys],[Y|Zs]) :- select(X,Ys,Zs). * rule number 2* 

?- select(4,[2,3,2,4,5,2,4],X]. 
X=[2,3,2,5,2,4] 

但我不明白它是如何找到正确的答案。在删除所有Y =!X之后,它变为规则编号1,其中:Xs=4,5,2,4,然后返回true。然后呢?如果它继续规则2,那么他也删除下一个“4”。如果它不继续规则1,那么How Zs是[2,3,2,5,2,4]?我认为我错过了一条基本规则。

+0

请注意,考虑到swi-prolog有51个追随者,你很难找到答案 - 呃,我添加了序言标签。 – 2011-06-12 09:23:24

+0

@Dhaivat Pandya:谢谢,很高兴知道。 – Tom 2011-06-12 09:37:44

回答

1

你可以通过考虑它将如何执行来理解为什么会发生这种情况。 所以,你必须:

% I use K here instead of X, so there is no 
% confusion with the X on the rules 
select(4,[2,3,2,4,5,2,4], K). 

首先,它会检查规则1,但4 != 2因此它会继续统治2.规则2,你有这些 “绑定”:

X = 2 
[Y | Ys] = [2, 3, 2, 4, 5, 2, 4] (which means Y = 2, Ys = [3, 2, 4, 5, 2, 4]) 
[Y | Zs] = [2 | Zs] (because Y was binded to 2) 

而且K绑定到[2 | Zs]而不是只是Zs。接下来的select呼叫将会是select(4, [3, 2, 4, 5, 2, 4], Zs)找到Zs等等。这就是为什么返回的结果是: K=[2,3,2,5,2,4]而不是你所期待的K=[5, 2, 4]