Did you know ... Search Documentation:
SWI-Prolog owl logo Predicate length/2
Availability:built-in
Source [ISO]length(?List, ?Length)
True if Length represents the number of elements in List. This predicate is a true relation and can be used to find the length of a list or produce a list (holding variables) of length Length. The predicate is non-deterministic, producing lists of increasing length if List is a partial list and Length is a variable.
?- length(List,4).
List = [_27940,_27946,_27952,_27958].
?- length(List,Length).
List = [], Length = 0 ;
List = [_24698], Length = 1 ;
List = [_24698,_25826], Length = 2
...

It raises errors if Length is bound to a non-integer or a negative integer or if List is neither a list nor a partial list. This error condition includes cyclic lists:139ISO demands failure here. We think an error is more appropriate.

?- A=[1,2,3|A], length(A,L).
ERROR: Type error: `list' expected ...

Covering an edge case, the predicate fails if the tail of List is equivalent to Length:140This is logically correct. An exception would be more appropriate, but to our best knowledge, current practice in Prolog does not describe a suitable candidate exception term.

?- List=[1,2,3|Length],length(List,Length).
false.
?- length(Length,Length).
false.

Examples

Generate solutions

Generate solutions

?- length(L, 3), maplist(between(0, 1), L).
L = [0, 0, 0] ;
L = [0, 0, 1] ;
L = [0, 1, 0] ;
L = [0, 1, 1] ;
L = [1, 0, 0] ;
L = [1, 0, 1] ;
L = [1, 1, 0] ;
L = [1, 1, 1].
Fill a list

Fill a list

?- length(L, 5), maplist(=(foo), L).
L = [foo, foo, foo, foo, foo].
Tags are associated to your profile if you are logged in|Report abuse
Tags:
  • listlength
LogicalCaptain said (2020年05月03日T13:08:18):0 upvotes 0 0 downvotes
Picture of user LogicalCaptain.

Doc needs fix

Maybe change the parameter name from Int to Length.

Notes

Some potentially useful notes

About length∕2

A length which never throws, and only fails

This is very low-hanging fruit, but may be useful:

Example

?- length(L,-1,lenient).
false.
?- length(L,-1,strict).
ERROR: Domain error: `not_less_than_zero' expected, found `-1'
?- length(L,-1,swi).
ERROR: Domain error: `not_less_than_zero' expected, found `-1'

Extension of length∕2: probe_length∕3 and probe_length∕4

probe_length(@MaybeList, ?Length, ?What)
probe_length(@MaybeList, ?Length, ?What, @Options)

probe_length∕3 and probe_length∕4 probe the length of an potentially open list without modifying it and tell you what the actual class of this maybe-list object is!

Examples:

?- probe_length([],Length,What).
Length = 0, What = closed.
?- probe_length([a,b,c],Length,What).
Length = 3, What = closed.
?- probe_length(_, Length, What).
Length = 0, What = var.
?- probe_length([a,b,c,d|foo], Length, What).
Length = 4, What = nonlist.
login to add a new annotation post.

AltStyle によって変換されたページ (->オリジナル) /