I am learning Prolog myself and recently came across a piece of notes:-
Example: nth/3
- for example, to find the nth element of a list we could use
nth([X|_],0,X).
nth([_|L],N,X) :- N1 is N - 1, nth(L,N1,X).
the 0th element of a list is the head of the list (first clause), otherwise we take the n-1th element of the tail of the list (second clause).
once we have found the nth element, we can’t find any more by backtracking.
nth([X|_],0,X).
nth([_|L],N,X) :- N1 is N - 1, !, nth(L,N1,X).
- adding a cut makes this clear and may be necessary for tail recursion optimisation.
However, when I use the trace function in Prolog, I found out that the calling sequences of these 2 pieces of codes are exactly the same.
Should I put the ! mark as follows instead?
nth([X|_],0,X) :- !.
nth([_|L],N,X) :- N1 is N - 1, nth(L,N1,X).