2
votes

Write a Prolog predicate everynth(N, X), that outputs every Nth element of the list X.

?- everynth(1, [1, 2, 3, 4, 5, 6]).
1 2 3 4 5 6
true.
?- everynth(2, [1, 2, 3, 4, 5, 6]).
2 4 6
true.

Here is what I tried, though I don't know to use recursion properly:

everynth(1, [X|_]) :-
    write(X),
    write(' ').
everynth(N, [_|H]) :-
    M is N - 1,
    everynth(M, H).
1
If this is homework, please tag it as "homework" and tell us what you have tried so far and what your problem is at the moment. We won't just give you a solution here. If it isn't, please describe what you are actually trying to achieve, and we can figure out the best way. - Kilian Foth
@user1400451 why do it with a loop and not with recursion? - Ido.Co
i think i can cut it down every time, recursion should be another way, but i dont really know recursion, because i just start study this. - user1400451
I replaced a , with a . in your code, it wasn't correct Prolog syntax. - m09

1 Answers

1
votes
:- use_module(library(dialect/hprolog)).


everynth(N,X) :- nth1(N,X,Elem),
                 write(Elem),
                 write(' '),
                 split_at(N,X,_,NewX),
                 everynthHelper(N,NewX).

everynthHelper(N,X) :- length(X,LengthX),
                       N > LengthX, !. 
everynthHelper(N,X) :- nth1(N,X,Elem),
                       write(Elem),
                       write(' '),
                       split_at(N,X,_,NewX),
                       everynthHelper(N,NewX).

I implemented a separate helper because the first successful call to everynthHelper/2 ensures that we will output true at the end.