Prolog在列表中查找索引并将其作为列表输出
问题描述:
我正在尝试实现谓词indices_zero(L,R)
,该谓词应在列表中找到零的所有位置,并在新列表中输出索引.
我正在尝试使用蓄电池.
例如:
I'm trying to implement a predicate indices_zero(L,R)
, which should find all positions of zeros in a list and output the indices in a new list.
I'm trying to do this with accumulators.
For example:
?-indices_zero([1,-2,3,0,5,0],R).
R=[4,6];
我实现了以下内容:
indices_zero(Ls,R):-
indices_zero(Ls,1,[],Result).
indices_zero([L|Ls],N,R,Result):-
L=:=0,
N1 is N+1,
indices-zero(Ls,N1,[N|R],Result).
indices_zero([L|Ls],N,R,Result):-
L=\=0,
N1 is N+1,
indices_zero(Ls,N1,R,Result).
indizes_zero([],_,Result,Result).
我不确定为什么我的实现无法正常工作.我想我的口渴条款 是不正确的,但我不知道该如何解决.
I'm not sure why my implementation doesn't work. I think my thirst clause isn't correct, but I don't know how to solve this.
答
尝试一下.
indices_zero(Ls, R) :-
indices_zero(Ls, 1, [], R).
indices_zero([], _, Result, Result).
indices_zero([0|T], N, Result_in, Result_out) :-
N1 is N + 1,
indices_zero(T, N1, [N|Result_in], Result_out).
indices_zero([H|T], N, Result_in, Result_out) :-
H \== 0,
N1 is N + 1,
indices_zero(T, N1, Result_in, Result_out).
?- indices_zero([1,-2,3,0,5,0],R).
R = [6, 4] ;
false.
这里是变体,可在回溯时构建结果.
请注意,答案中索引的顺序现在按升序排列.
Here is a variation that builds the result while backtracking.
Notice the order of the indices in the answer are now in ascending order.
indices_zero(Ls,R) :-
indices_zero(Ls,1,R).
indices_zero([],_,[]).
indices_zero([0|T], N, [N|Result]) :-
N1 is N + 1,
indices_zero(T, N1, Result).
indices_zero([H|T], N, Result) :-
H \== 0,
N1 is N + 1,
indices_zero(T, N1, Result).
?- indices_zero([1,-2,3,0,5,0],R).
R = [4, 6] ;
false.