我是 Prolog 的新手,我在遞回和嵌套串列方面遇到了麻煩。
我想要一個謂詞getCommon(Number, List, X),它執行以下操作:
getCommon(2, [[2,3], [2,5], [3,5]], X).
X = [[2,3], [2,5]].
我試過了,但它回傳一個空串列,我很困惑為什么:
getCommon(_,[],_).
getCommon(Elem, [PointsH|PointsT], CommonPoints):-
nth0(0, PointsH, CurrElem),
(CurrElem = Elem -> append(CommonPoints,[PointsH],NewCommonPoints) ;append(CommonPoints,[],NewCommonPoints)),
getCommon(Elem, PointsT, NewCommonPoints).
uj5u.com熱心網友回復:
您的代碼不起作用,因為遞回基本情況沒有很好地定義,還因為謂詞append/3沒有正確使用。試試下面的代碼:
get_common(_, [], []).
get_common(K, [[K,Y]|Points], [[K,Y]|Rest]) :-
get_common(K, Points, Rest).
get_common(K, [[X,_]|Points], Rest) :-
dif(K,X),
get_common(K, Points, Rest).
例子:
?- get_common(2, [[2,3], [3,2], [2,5], [3,7]], Common).
Common = [[2, 3], [2, 5]] ;
false.
?- get_common(3, [[2,3], [3,2], [2,5], [3,7]], Common).
Common = [[3, 2], [3, 7]] ;
false.
?- get_common(2, [[2,3], [K,2], [2,5], [3,7]], Common).
K = 2,
Common = [[2, 3], [2, 2], [2, 5]] ;
Common = [[2, 3], [2, 5]],
dif(K, 2) ;
false.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/455704.html
上一篇:遍歷串列時閉包函式出錯
