Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Length in Prolog

Tags:

list

prolog

clpfd

I am beginner in Prolog programming. I wrote this program to calculate the length of a list. Why is below program wrong?

length(0, []).
length(L+l, H|T) :- length(L, T).

I wrote below program and it works correctly.

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

when I changed the order, I got an error. Why?

length([], 0).
length([H|T], N) :- N is N1+1, length(T, N1).
like image 619
Fery Avatar asked Oct 07 '13 17:10

Fery


1 Answers

len([], LenResult):-
    LenResult is 0.

len([X|Y], LenResult):-
    len(Y, L),
    LenResult is L + 1.
like image 172
garciparedes Avatar answered Sep 28 '22 01:09

garciparedes