Next: , Previous: , Up: lists fold   [Index]


23.8.5 Folding pairs

Function: pair-fold kons knil circ1 circ2 ...

Analogous to fold, but kons is applied to successive sublists of the lists, rather than successive elements; that is, kons is applied to the pairs making up the lists, giving this (tail) recursion:

(pair-fold kons knil ell) ≡ (let ((tail (cdr ell)))
                               (pair-fold kons
                                          (kons ell knil)
                                          tail))
(pair-fold kons knil '()) ≡ knil

For finite lists, the kons function may reliably apply set-cdr! to the pairs it is given without altering the sequence of execution.

Examples:

(pair-fold (lambda (elm knil)
             (cons (car elm) knil))
           '(999)
           '(1 2 3))
⇒ (3 2 1 999)

;;; destructively reverse a list
(pair-fold (lambda (pair tail)
             (set-cdr! pair tail)
             pair)
           '()
           '(0 1 2 3 4 5))
⇒ (5 4 3 2 1 0)

At least one of the list arguments must be finite.

Function: pair-fold* kons knil circ1 circ2 ...

Hold the same relationship with fold* that pair-fold holds with fold; obey the recursion:

(pair-fold* kons knil lis) ≡
    (kons lis (pair-fold* kons knil (cdr lis)))
(pair-fold* kons knil '()) ≡ knil

example:

(pair-fold* cons '() '(a b c))
⇒ ((a b c) (b c) (c))

At least one of the list arguments must be finite.

Examples:

(pair-fold* (lambda (elm knil)
              (cons (car elm) knil))
            '(999)
            '(1 2 3))
⇒ (1 2 3 999)

(pair-fold* (lambda (pair tail)
              (set-cdr! pair tail)
              pair)
            '()
            '(0 1 2 3 4 5))
⇒ (0 1 2 3 4 5)

(pair-fold* (lambda (a b c knil)
              (cons (list (car a)
                          (car b)
                          (car c))
                    knil))
            '(999)
            '(1 2 3)
            '(10 20 30)
            '(100 200 300))
⇒ '((1 10 100)
     (2 20 200)
     (3 30 300)
     999)

Next: , Previous: , Up: lists fold   [Index]