next up previous
Next: Exercises Up: Arithmetic in Prolog Previous: Arithmetic in Prolog

length/2

It is often useful to be able to calculate (or check) the length of a list. With arithmetic operators this is something that we can now do. The base is the empty list, which is obviously of length 0. This give us the Prolog clause:
length([ ], 0).
The recursion simply requires that we add 1 for each item on the list:[*]
length([H|T], N):-
   length(T, N1),
   N is N1 + 1.


Steve Harlow 2001-11-26