Infernal
Infernal

Reputation: 45

Prolog - Give out every nth element of a list

I'm working on a Prolog program which should load every nth element of a list into another list. For example:

?- pred([a,b,c,d,e,f,g,h,i,j],3,R) => 
R = [c,f,i]

Where pred is the predicate I'm attempting to implement.

But I honestly don't know how to do it. I know that I need a counter, which represents the current position of my Head, so it's gonna be a /4 predicate summarized into a /3 one later one, like nth(list,number,result) :- nth(list,number,result,counter) or similiar.

Though, I don't know how to give the head a position number that can reset itself. Because once it hits n (let's say n=3, which is the c in the list), it has to turn back to 1 logically and count again up to 3, give out the element, and so on.

How can I work around these specific problems in my implementation?

Upvotes: 0

Views: 1096

Answers (1)

Limmen
Limmen

Reputation: 1457

An example of how this could be implemented:

nth_pos(L, N, R):-
    nth_pos(L, 1, N, [], R).

nth_pos([], I, N, Acc, Acc).

nth_pos([H|T], I, N, Acc, R):-
    I =:= N,
    append(Acc, [H], Acc2),
    I2 is 1,   
    nth_pos(T, I2, N, Acc2, R).

nth_pos([H|T], I, N, Acc, R):-
    I < N,
    I2 is I + 1,   
    nth_pos(T, I2, N, Acc, R).

Test-run:

?- nth_pos([a,b,c,d,e,f,g,h,i,j],3,R).
R = [c, f, i] .

?- nth_pos([a,b,c,d,e,f,g,h,i,j],1,R).
R = [a, b, c, d, e, f, g, h, i|...]

But I honestly don't know how to do it. I know that I need a counter, which represents the current position of my Head, so it's gonna be a /4 predicate summarized into a /3 one later one, like nth(list,number,result) :- nth(list,number,result,counter) or similiar.

Yes you are on the right track, note that an accumulator is used as well to build up the list so we get pred/5. Hope it helps. Note that this is not the only way to solve it.

Upvotes: 1

Related Questions