Prolog find indices in a list and output them as a

2019-07-28 04:58发布

问题:

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];

I have implemented following:

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.

回答1:

Try 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.


标签: list prolog