2.4 Value accumulation

2.4.1 Combining accumulation clauses

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. For example, since both thecollect andappend constructs accumulate objects into a list that is returned from a loop, you can combine them safely.

;; Collect every name and the kids in one list by using 
;; COLLECT and APPEND.
> (loop for name in '(fred sue alice joe june)
        for kids in '((bob ken) () () (kris sunshine) ())
        collect name
        append kids)
(FRED BOB KEN SUE ALICE JOE KRIS SUNSHINE JUNE)

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 functionvalues, 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
        finally
        (return
         (values (round total-age name-count)
                  name-and-age-list)))
19
(FRED 22 SUE 26 ALICE 19 JOE 20 JUNE 10)


The Loop Facility - 9 SEP 1996

Generated with Harlequin WebMaker