2012-02-15 39 views
0

內置謂詞成員(x,List)檢查成員是否存在於列表中,但是當列表中有列表時,它只檢查第一個深度。我試圖準確找出一個成員是在什麼深度,例如:如何在序言中找到成員在列表中的深度?

?- memberDepth(a, [b, c, [d], [[e, f, [], [g], a], j], [k]], Depth). 
Depth = 3 . 

因此,基本上,它發現「A」列表中的第一個實例的深度。如果成員不存在,它會返回深度= 0。這也將是有用的,如果我能找到該成員的所有實例的深度,從而,例如:

?- memberDepthAll(a, [b, c, [a], [[e], a], [[a]]], Depth). 
Depth = 2 ; 
Depth = 2 ; 
Depth = 3 ; 
Depth = 0 ; 
false. 

我很新的序言,所以任何幫助將不勝感激。

+2

標記爲家庭作業。這個問題非常相似,其實—事實上是相同的,實際上—到今天上午的問題,http://stackoverflow.com/questions/9287942/prolog-list-search,海報維護它的地方是他自己的東西。我很懷疑。 – 2012-02-16 01:04:20

回答

0

您應該通過檢查列表中的每個元素來處理它是否是原子。
如果是這樣,檢查它是否等於'a',否則,它可能是一個列表,遞歸調用「memberDepth」。
更多關於原子here

memberDepth(X,[L|Ls],Depth) :- 
    atom(L),!,      % true iff L is an atom 
    ... 
memberDepth(X,[L|Ls],Depth) :- 
    ... 
2

需要注意的是,如果在任何點的第二個參數是不是一個名單,沒有任何規則將匹配。此外,您可以使用成員來檢查頂層,但由於我們必須分解列表以進一步深入,因此我會逐個檢查每個元素,這樣可以避免重複工作或需要輔助謂詞。

% First, check the first element of the list 
memberDepth(X,[X|_],0). 
% Next search inside the first element of the list (hence the +1) 
memberDepth(X,[H|_],D1) :- memberDepth(X,H,D), D1 is D+1. 
% FInally, search the rest of the list 
memberDepth(X,[_|T],D) :- memberDepth(X,T,D). 
相關問題