List length 3

Description

Determining the length of a list.

Source: The Art of Prolog

Download

Program source code: list_length_3.pl

Listing

/*
   mylength(Xs,N) :- The list Xs has length N.
*/
   mylength(Xs,N) :- nonvar(Xs), length1(Xs,N).
   mylength(Xs,N) :- var(Xs), nonvar(N), length2(Xs,N).
 
/*
   length1(Xs,N) :- N is the length of the list Xs.
*/
     length1([X|Xs],N) :- length1(Xs,N1), N is N1+1.
     length1([],0).
 
/*
   length2(Xs,N) :- Xs is a list of length N.
*/
     length2([X|Xs],N) :- N > 0, N1 is N-1, length2(Xs,N1).
     length2([],0).
 
%  Program 10.2    A multipurpose length program

Comments

pl/prolog/pllib/list_length_3.txt · ostatnio zmienione: 2019/06/27 15:50 (edycja zewnętrzna)
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0