Nth0/3 implementaion in swi-prolog

I came across this code, which I assume will be faster than iterating one element at a time.

nth0_det(0, [Elem|_], Elem) :- !.
nth0_det(1, [_,Elem|_], Elem) :- !.
nth0_det(2, [_,_,Elem|_], Elem) :- !.
nth0_det(3, [_,_,_,Elem|_], Elem) :- !.
nth0_det(4, [_,_,_,_,Elem|_], Elem) :- !.
nth0_det(5, [_,_,_,_,_,Elem|_], Elem) :- !.
nth0_det(N, [_,_,_,_,_,_   |Tail], Elem) :-
    M is N - 6,
    M >= 0,
    nth0_det(M, Tail, Elem).

Is there any particular reason the unrolling stopped at 6 elements? Is it just chosen arbitrarily?
Here it was first introduced https://github.com/SWI-Prolog/swipl-devel/commit/69feecc5228b933d9800ce07e125cf889271e012

This is just a pure guest (WAG) but sometimes they are correct.

Obviously such generators could could go on until memory is exhausted. So the ISO standard for Prolog set the limit on the number of arguments for such predicates. I don’t think 6 is the limit because lambdas use 7.

I tried to find the exact wording in the standard but searching for it was not productive. There were over a thousand hits for 6 and then trying to read each for comprehension was exhausting.

I know the concept was noted in a post on this site and that if you look for other code such as the lambdas that accept a number of arguments it might put you in the ball park of where it is defined.


I do not understand how the limit on number of parameters will apply in this situation.

OK I see what you are asking now. (For others the question was edited)

I agree that the limit for augments does not apply for list AFAIK, so the decision AFAIK was arbitrarily made by the creator of the code.

However in many programming languages, such limits are common and even defined in the standard.

The main reason I know of for limiting the number to less than 10 in any programming language is that if you need more than that you really should rethink the design of your code; most likely a change in the data structure.

In https://www.swi-prolog.org/pldoc/man?section=deep-indexing, there is
Currently, the depth of indexing is limited to 7 levels.
A list of length more than 6 is essentially a term of depth more than 6, is this why the loop is unrolled only 6 times?

I am not 100% sure. If nth0_det/3 is called with mode (+,…), even
not much indexing is needed, ordinary first argument indexing is enough.
So it might be an arbitrary unrolling, and even work well among a large
range of Prolog systems, that have first argument indexing.