home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 9 / 09.iso / l / l217 / 2.ddi / EXAMPLES / CH08EX03.PRO < prev    next >
Encoding:
Prolog Source  |  1990-03-26  |  858 b   |  29 lines

  1. /*
  2.    Copyright (c) 1986, 90 by Prolog Development Center
  3. */
  4.    
  5. domains
  6.    list = integer* /* or whatever type you want to use */
  7.  
  8. predicates
  9.    length_of(list, integer, integer)
  10.  
  11. clauses
  12. /* * * * * * * * * * * * * * * * * * * * * * *
  13.  * If the list is empty, bind the second arg *
  14.  *   (the result) to the third (the counter).*
  15.  * * * * * * * * * * * * * * * * * * * * * * */
  16.    length_of([], Result, Result).
  17.  
  18. /* * * * * * * * * * * * * * * * * * * * * * * * * * *
  19.  * Otherwise, add 1 to counter and recurse, binding  *
  20.  * Result in this invocation to Result in the next.  *
  21.  * * * * * * * * * * * * * * * * * * * * * * * * * * */
  22.    length_of([_|T], Result, Counter) :-
  23.       NewCounter = Counter + 1,
  24.       length_of(T, Result, NewCounter).
  25.  
  26. goal
  27.    length_of([1, 2, 3], L, 0), /* start with Counter = 0 */
  28.    write(L), nl.
  29.