如何获取嵌套列表中的所有元素,其中每个列表的第一个元素是特定数字?
How to get all elements in a nested list where the first element of each list is a particular number?
我是 Prolog 的新手,我在递归和嵌套列表方面遇到了问题。
我想要一个名为 getCommon(Number, List, X)
的谓词,它执行以下操作:
getCommon(2, [[2,3], [2,5], [3,5]], X).
X = [[2,3], [2,5]].
我试过了,但它 returns 是一个空列表,我很困惑为什么:
getCommon(_,[],_).
getCommon(Elem, [PointsH|PointsT], CommonPoints):-
nth0(0, PointsH, CurrElem),
(CurrElem = Elem -> append(CommonPoints,[PointsH],NewCommonPoints) ;append(CommonPoints,[],NewCommonPoints)),
getCommon(Elem, PointsT, NewCommonPoints).
您的代码不起作用,因为递归基本情况未明确定义,还因为谓词 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.
我是 Prolog 的新手,我在递归和嵌套列表方面遇到了问题。
我想要一个名为 getCommon(Number, List, X)
的谓词,它执行以下操作:
getCommon(2, [[2,3], [2,5], [3,5]], X).
X = [[2,3], [2,5]].
我试过了,但它 returns 是一个空列表,我很困惑为什么:
getCommon(_,[],_).
getCommon(Elem, [PointsH|PointsT], CommonPoints):-
nth0(0, PointsH, CurrElem),
(CurrElem = Elem -> append(CommonPoints,[PointsH],NewCommonPoints) ;append(CommonPoints,[],NewCommonPoints)),
getCommon(Elem, PointsT, NewCommonPoints).
您的代码不起作用,因为递归基本情况未明确定义,还因为谓词 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.