Prolog Size Procedure

I am new to Prolog and not so good when it comes to recursive algorithms as it is, so I get confused with the following two articles:

size([], 0).
size([H|T], N) :- size(T, N1), N is N1+1.

I am having trouble tracking this issue:

?- size([a,b,c,d], N).

This will be standardized with the second sentence to form:

size([a,b,c,d], N) :- size([b,c,d], N1), N is N1+1.

But I'm confused with Nis N1+1, as these variables are never combined. What values ​​do these variables take?

It would be useful to get any help on this or a simple trace of this algorithm.

+2
source share
1 answer

N is N1 + 1, since these variables are never unified.

, , , .. . , . , REPL:

?- N = N1.
N = N1.

while N N1 (), ; N1 , N . , :

?- [H|T] = L, L = [1|M], writeln(H).
1
H = 1,
T = M,
L = [1|M].

, N N1+1! is N1+1 , N. , size([b,c,d],N1) , N1.

, :

size([a,b,c,d],N).
          size([b,c,d],N1)
               size([c,d],N1)
                   size([d],N1)
                        size([],0)
                        N is 0+1.
                   N is 1+1.
               N is 2+1.
          N is 3+1.

, ; , .

, N1 , is . - :

size([],0).
size([_|T], 1+ N1):-size(T,N1).

:

?- size([1,2],N).
N = 0+1+1.

, ? N, . size([1,2],N), Result is N. , 0+1+1+1+1+...... , . , , . .

+4

All Articles