General
Material
Lecture 1
Lecture 2
Lecture 3
Lecture 4
Lecture 5

Hint

The predicate should recursively work its way through the list. While it is doing so it has to keep track which position of the original list the head of the current input list corresponds to.

This means that the recursive predicate needs four arguments: 1) the position of the element that we are looking for, 2) the position of the element which we are currently looking at, 3) the input list, which will be reduced by one element in each recursive step, and 4) the output. Recursion should stop when the first and the second argument are the same.

The exercise asked you to define the 3-place predicate get_nth_element(+N,+List,?R). But all this predicate will do is to call the 4-place version which we just described. This call has to provide an initial instantiation for the second argument of the 4-place predicate. The 4-place predicate will do most of the real work.

This technique is also used when using accumulators which are described in this exercise.

Solution

Back to the exercise.