chickadee » srfi-116 » ifold

ifold konx knil ilist1 ilist2 ...procedure

The fundamental ilist iterator.

First, consider the single ilist-parameter case. If ilist1 is (e1 e2 ... en), then this procedure returns

(kons en ... (kons e2 (kons e1 knil)) ... )

That is, it obeys the (tail) recursion

(ifold kons knil lis) ;=> (ifold kons (kons (icar lis) knil) (icdr lis))
(ifold kons knil '()) ;=> knil


(ifold + 0 lis)             ; Add up the elements of LIS.
(ifold ipair '() lis)       ; Reverse LIS.
(ifold ipair tail rev-head) ; See APPEND-REVERSE.

;; How many symbols in LIS?
(ifold (lambda (x count) (if (symbol? x) (+ count 1) count))

;; Length of the longest string in LIS:
(ifold (lambda (s max-len) (max max-len (string-length s)))

If n ilist arguments are provided, then the kons function must take n+1 parameters: one element from each ilist, and the "seed" or fold state, which is initially knil. The fold operation terminates when the shortest ilist runs out of values:

(ifold ipair* '() (iq a b c) (iq 1 2 3 4 5)) ;=> (c 3 b 2 a 1)