Path: utzoo!attcan!uunet!mcsun!hp4nl!swi.psy.uva.nl!anjo From: anjo@swi.psy.uva.nl (Anjo Anjewierden) Newsgroups: comp.lang.prolog Subject: Definition of list_length/2 Message-ID: <2733@swi.swi.psy.uva.nl> Date: 13 Feb 90 15:27:17 GMT Reply-To: anjo@swi.psy.uva.nl () Organization: SWI, UvA, Amsterdam Lines: 38 Below is a definition of list_length/2 (length/2 in Edinburgh compatibles). I would like to know whether there is a better/shorter solution that handles all cases and is deterministic given certain calling patterns (see definition below). -- Anjo. % list_length(?List, ?Length) % % List is a list of length Length. % % Note: list_length/2 is deterministic if the arguments are % sufficiently instantiated (i.e. if Length is given and/or % List is a proper list), otherwise it generates alternative % solutions on backtracking. list_length(List, Length) :- integer(Length), !, list_length_det(List, Length). % Always deterministic list_length(List, Length) :- var(Length), list_length_non(List, Length). % Possibly non-deterministic /* list_length_non(List, N) :- % This clause only if the Prolog List == [], !, % does not perform clause indexing. N = 0. */ list_length_non([], 0). list_length_non([_|Xs], N) :- list_length_non(Xs, M), N is M+1. list_length_det([], 0) :- !. list_length_det([_|Xs], N) :- M is N-1, list_length_det(Xs, M).