[ library(lists) | Reference Manual | Alphabetic Index ]
length(?List, ?N)
Succeeds if the length of list List is N.
- ?List
- List or variable.
- ?N
- Integer or variable.
Description
   Unifies N with the length of list List.  length/2 can be used to create
   a list List of length N. The definition of this Prolog library predicate
   is:
length(List, Length) :-
        ( var(Length) ->
          length(List, 0, Length)
        ;
          Length >= 0,
          length1(List, Length) ).
length([], Length, Length).
length([_|L], N, Length) :-
        N1 is N+1,
        length(L, N1, Length).
length1([], 0) :- !.
length1([_|L], Length) :-
        N1 is Length-1,
        length1(L, N1).
   This predicate does not perform any type testing functions.
	
Modes and Determinism
- length(+, +) is semidet
- length(+, -) is det
- length(-, +) is det
- length(-, -) is multi
Fail Conditions
   Fails if the length of list List does not unify with N.
Resatisfiable
   Yes.
Examples
Success:
  length([1,2,3],N).   (gives N=3).
  length([1,2,1,X],N). (gives X=_g84; N=4).
  length(L,2).         (gives L=[_g62,_g72]). % creates list
Fail:
  length([1,2,3],2).
See Also
append / 3