I don't really understand how recursion works in Prolog. Assume you have the following two functions:
my_length([],0).
my_length([_|T], Length) :-
my_length(T, T_length),
Length is T_length + 1.
my_nth0(Position, [Element|_], Element, Position).
my_nth0(Position, [_|Tail], X, CurrentPos) :-
NextPos is CurrentPos + 1,
my_nth0(Position, Tail, X, NextPos).
I understand my_nth0: every time you call the function recursively, you increase NextPos by 1. However, I don't understsand my_length. I'd write it like this:
my_length([],0).
my_length([_|T], Length) :-
T_Length is Length + 1.,
my_length(T, T_length).
That seems to follow the same style as my_nth0. However, the first function implementation, which seems to be correct, does exactly the opposite (it basically says T_length is Length - 1). Why does this work?
my_nth0/4is needlessly inefficient on backtracking. Compare?- length(Es,100), time((my_nth0(0,Es,X,0),false)).with?- length(Es,100), time((nth0(0,Es,X),false).