Next: , Previous: , Up: Loop   [Contents][Index]

15.25.8 Value Accumulation

Clauses that accumulate values in lists and return them.

Clauses that accumulate and return numerical values

Accumulation Variable

The preposition keyword

Combining Accumulations

You can combine value-returning accumulation clauses in a loop if all the clauses accumulate the same type of data object. By default, the Loop Facility returns only one value; thus, the data objects collected by multiple accumulation clauses as return values must have compatible types.

;;; Collect every name and the kids in one list by using
(loop for name in '(fred sue alice joe june)
      for kids in '((bob ken) () () (kris sunshine) ())
      collect name
      append kids)

[In the preceding example, note that the items accumulated by the ‘collect’ and ‘append’ clauses are interleaved in the result list, according to the order in which the clauses were executed.-GLS]

Multiple clauses that do not accumulate the same type of data object can coexist in a loop only if each clause accumulates its values into a different user-specified variable. Any number of values can be returned from a loop if you use the Common Lisp function values, as the next example shows:

;;; Count and collect names and ages.
(loop for name in '(fred sue alice joe june)
      as age in '(22 26 19 20 10)
      append (list name age) into name-and-age-list
      count name into name-count
      sum age into total-age
        (return (values (round total-age name-count)
; => 19 and (FRED 22 SUE 26 ALICE 19 JOE 20 JUNE 10)



[There is no semantic difference between the “ing” keywords and their non-“ing” counterparts. They are provided purely for the sake of stylistic diversity among users. I happen to prefer the non-“ing” forms-when I use loop at all.-GLS]

Next: Variable Initializations, Previous: End-Test Control, Up: Loop   [Contents][Index]