Why length/2 predicate in prolog can produce infinite number of lengths?

Viewed 191

When I apply this query:

? length(P, _).

P = [] ? ;

P = [_] ? ;

P = [_,_] ? ;

P = [_,_,_] ? ;

P = [_,_,_,_] ?

I have that result. How does this works?

1 Answers

Through choice points. As soon as a predicate has more than one clause, roughly a choice point is created:

length([], 0).
length([_|L], M) :- length(L, N), M is N+1.

These choice points then give different derivations by the Prolog interpreter. Here is a derivation screenshot in Tau Prolog sandbox:

enter image description here

Hold on, I guess I need to raise an issue, this derivation screenshot shows a little bit too much. Synthetic (=)/2 and control (,)/2.

Related