Debian Codegraph @

%3a1/srfi-1-reference.scm

raw symbols SCIP
1 ;;; SRFI-1 list-processing library -*- Scheme -*-
2 ;;; Reference implementation
3 ;;;
4 ;;; Copyright (c) 1998, 1999 by Olin Shivers. You may do as you please with
5 ;;; this code as long as you do not remove this copyright notice or
6 ;;; hold me liable for its use. Please send bug reports to [email protected].
7 ;;; -Olin
8
9 ;;; Copyright (c) Jéssica Milaré, 2018. You may do as you please with
10 ;;; this code as long as you do not remove this copyright notice or
11 ;;; hold me liable for its use.
12
13 ;;; This is a library of list- and pair-processing functions. I wrote it after
14 ;;; carefully considering the functions provided by the libraries found in
15 ;;; R4RS/R5RS Scheme, MIT Scheme, Gambit, RScheme, MzScheme, slib, Common
16 ;;; Lisp, Bigloo, guile, T, APL and the SML standard basis. It is a pretty
17 ;;; rich toolkit, providing a superset of the functionality found in any of
18 ;;; the various Schemes I considered.
19
20 ;;; This implementation is intended as a portable reference implementation
21 ;;; for SRFI-1. See the porting notes below for more information.
22
23 ;;; Exported:
24 ;;; xcons tree-copy make-list list-tabulate cons* list-copy
25 ;;; proper-list? circular-list? dotted-list? not-pair? null-list? list=
26 ;;; circular-list length+
27 ;;; iota
28 ;;; first second third fourth fifth sixth seventh eighth ninth tenth
29 ;;; car+cdr
30 ;;; take drop
31 ;;; take-right drop-right
32 ;;; take! drop-right!
33 ;;; split-at split-at!
34 ;;; last last-pair
35 ;;; zip unzip1 unzip2 unzip3 unzip4 unzip5
36 ;;; count
37 ;;; append! append-reverse append-reverse! concatenate concatenate!
38 ;;; unfold fold pair-fold reduce
39 ;;; unfold-right fold-right pair-fold-right reduce-right
40 ;;; append-map append-map! map! pair-for-each filter-map map-in-order
41 ;;; filter partition remove
42 ;;; filter! partition! remove!
43 ;;; find find-tail any every list-index
44 ;;; take-while drop-while take-while!
45 ;;; span break span! break!
46 ;;; delete delete!
47 ;;; alist-cons alist-copy
48 ;;; delete-duplicates delete-duplicates!
49 ;;; alist-delete alist-delete!
50 ;;; reverse!
51 ;;; lset<= lset= lset-adjoin
52 ;;; lset-union lset-intersection lset-difference lset-xor lset-diff+intersection
53 ;;; lset-union! lset-intersection! lset-difference! lset-xor! lset-diff+intersection!
54 ;;;
55 ;;; In principle, the following R4RS list- and pair-processing procedures
56 ;;; are also part of this package's exports, although they are not defined
57 ;;; in this file:
58 ;;; Primitives: cons pair? null? car cdr set-car! set-cdr!
59 ;;; Non-primitives: list length append reverse cadr ... cddddr list-ref
60 ;;; memq memv assq assv
61 ;;; (The non-primitives are defined in this file, but commented out.)
62 ;;;
63 ;;; These R4RS procedures have extended definitions in SRFI-1 and are defined
64 ;;; in this file:
65 ;;; map for-each member assoc
66 ;;;
67 ;;; The remaining two R4RS list-processing procedures are not included:
68 ;;; list-tail (use drop)
69 ;;; list? (use proper-list?)
70
71
72 ;;; A note on recursion and iteration/reversal:
73 ;;; Many iterative list-processing algorithms naturally compute the elements
74 ;;; of the answer list in the wrong order (left-to-right or head-to-tail) from
75 ;;; the order needed to cons them into the proper answer (right-to-left, or
76 ;;; tail-then-head). One style or idiom of programming these algorithms, then,
77 ;;; loops, consing up the elements in reverse order, then destructively
78 ;;; reverses the list at the end of the loop. I do not do this. The natural
79 ;;; and efficient way to code these algorithms is recursively. This trades off
80 ;;; intermediate temporary list structure for intermediate temporary stack
81 ;;; structure. In a stack-based system, this improves cache locality and
82 ;;; lightens the load on the GC system. Don't stand on your head to iterate!
83 ;;; Recurse, where natural. Multiple-value returns make this even more
84 ;;; convenient, when the recursion/iteration has multiple state values.
85
86 ;;; Porting:
87 ;;; This is carefully tuned code; do not modify casually.
88 ;;; - It is careful to share storage when possible;
89 ;;; - Side-effecting code tries not to perform redundant writes.
90 ;;;
91 ;;; That said, a port of this library to a specific Scheme system might wish
92 ;;; to tune this code to exploit particulars of the implementation.
93 ;;; The single most important compiler-specific optimisation you could make
94 ;;; to this library would be to add rewrite rules or transforms to:
95 ;;; - transform applications of n-ary procedures (e.g. LIST=, CONS*, APPEND,
96 ;;; LSET-UNION) into multiple applications of a primitive two-argument
97 ;;; variant.
98 ;;; - transform applications of the mapping functions (MAP, FOR-EACH, FOLD,
99 ;;; ANY, EVERY) into open-coded loops. The killer here is that these
100 ;;; functions are n-ary. Handling the general case is quite inefficient,
101 ;;; requiring many intermediate data structures to be allocated and
102 ;;; discarded.
103 ;;; - transform applications of procedures that take optional arguments
104 ;;; into calls to variants that do not take optional arguments. This
105 ;;; eliminates unnecessary consing and parsing of the rest parameter.
106 ;;;
107 ;;; These transforms would provide BIG speedups. In particular, the n-ary
108 ;;; mapping functions are particularly slow and cons-intensive, and are good
109 ;;; candidates for tuning. I have coded fast paths for the single-list cases,
110 ;;; but what you really want to do is exploit the fact that the compiler
111 ;;; usually knows how many arguments are being passed to a particular
112 ;;; application of these functions -- they are usually explicitly called, not
113 ;;; passed around as higher-order values. If you can arrange to have your
114 ;;; compiler produce custom code or custom linkages based on the number of
115 ;;; arguments in the call, you can speed these functions up a *lot*. But this
116 ;;; kind of compiler technology no longer exists in the Scheme world as far as
117 ;;; I can see.
118 ;;;
119 ;;; Note that this code is, of course, dependent upon standard bindings for
120 ;;; the R5RS procedures -- i.e., it assumes that the variable CAR is bound
121 ;;; to the procedure that takes the car of a list. If your Scheme
122 ;;; implementation allows user code to alter the bindings of these procedures
123 ;;; in a manner that would be visible to these definitions, then there might
124 ;;; be trouble. You could consider horrible kludgery along the lines of
125 ;;; (define fact
126 ;;; (let ((= =) (- -) (* *))
127 ;;; (letrec ((real-fact (lambda (n)
128 ;;; (if (= n 0) 1 (* n (real-fact (- n 1)))))))
129 ;;; real-fact)))
130 ;;; Or you could consider shifting to a reasonable Scheme system that, say,
131 ;;; has a module system protecting code from this kind of lossage.
132 ;;;
133 ;;; This code does a fair amount of run-time argument checking. If your
134 ;;; Scheme system has a sophisticated compiler that can eliminate redundant
135 ;;; error checks, this is no problem. However, if not, these checks incur
136 ;;; some performance overhead -- and, in a safe Scheme implementation, they
137 ;;; are in some sense redundant: if we don't check to see that the PROC
138 ;;; parameter is a procedure, we'll find out anyway three lines later when
139 ;;; we try to call the value. It's pretty easy to rip all this argument
140 ;;; checking code out if it's inappropriate for your implementation -- just
141 ;;; nuke every call to CHECK-ARG.
142 ;;;
143 ;;; On the other hand, if you *do* have a sophisticated compiler that will
144 ;;; actually perform soft-typing and eliminate redundant checks (Rice's systems
145 ;;; being the only possible candidate of which I'm aware), leaving these checks
146 ;;; in can *help*, since their presence can be elided in redundant cases,
147 ;;; and in cases where they are needed, performing the checks early, at
148 ;;; procedure entry, can "lift" a check out of a loop.
149 ;;;
150 ;;; Finally, I have only checked the properties that can portably be checked
151 ;;; with R5RS Scheme -- and this is not complete. You may wish to alter
152 ;;; the CHECK-ARG parameter checks to perform extra, implementation-specific
153 ;;; checks, such as procedure arity for higher-order values.
154 ;;;
155 ;;; The code has only these non-R4RS dependencies:
156 ;;; A few calls to an ERROR procedure;
157 ;;; Uses of the R5RS multiple-value procedure VALUES and the m-v binding
158 ;;; RECEIVE macro (which isn't R5RS, but is a trivial macro).
159 ;;; Many calls to a parameter-checking procedure check-arg:
160 ;;; (define (check-arg pred val caller)
161 ;;; (let lp ((val val))
162 ;;; (if (pred val) val (lp (error "Bad argument" val pred caller)))))
163 ;;;
164 ;;; Most of these procedures use the NULL-LIST? test to trigger the
165 ;;; base case in the inner loop or recursion. The NULL-LIST? function
166 ;;; is defined to be a careful one -- it raises an error if passed a
167 ;;; non-nil, non-pair value. The spec allows an implementation to use
168 ;;; a less-careful implementation that simply defines NULL-LIST? to
169 ;;; be NOT-PAIR?. This would speed up the inner loops of these procedures
170 ;;; at the expense of having them silently accept dotted lists.
171
172 ;;; A note on dotted lists:
173 ;;; I, personally, take the view that the only consistent view of lists
174 ;;; in Scheme is the view that *everything* is a list -- values such as
175 ;;; 3 or "foo" or 'bar are simply empty dotted lists. This is due to the
176 ;;; fact that Scheme actually has no true list type. It has a pair type,
177 ;;; and there is an *interpretation* of the trees built using this type
178 ;;; as lists.
179 ;;;
180 ;;; I lobbied to have these list-processing procedures hew to this
181 ;;; view, and accept any value as a list argument. I was overwhelmingly
182 ;;; overruled during the SRFI discussion phase. So I am inserting this
183 ;;; text in the reference lib and the SRFI spec as a sort of "minority
184 ;;; opinion" dissent.
185 ;;;
186 ;;; Many of the procedures in this library can be trivially redefined
187 ;;; to handle dotted lists, just by changing the NULL-LIST? base-case
188 ;;; check to NOT-PAIR?, meaning that any non-pair value is taken to be
189 ;;; an empty list. For most of these procedures, that's all that is
190 ;;; required.
191 ;;;
192 ;;; However, we have to do a little more work for some procedures that
193 ;;; *produce* lists from other lists. Were we to extend these procedures to
194 ;;; accept dotted lists, we would have to define how they terminate the lists
195 ;;; produced as results when passed a dotted list. I designed a coherent set
196 ;;; of termination rules for these cases; this was posted to the SRFI-1
197 ;;; discussion list. I additionally wrote an earlier version of this library
198 ;;; that implemented that spec. It has been discarded during later phases of
199 ;;; the definition and implementation of this library.
200 ;;;
201 ;;; The argument *against* defining these procedures to work on dotted
202 ;;; lists is that dotted lists are the rare, odd case, and that by
203 ;;; arranging for the procedures to handle them, we lose error checking
204 ;;; in the cases where a dotted list is passed by accident -- e.g., when
205 ;;; the programmer swaps a two arguments to a list-processing function,
206 ;;; one being a scalar and one being a list. For example,
207 ;;; (member '(1 3 5 7 9) 7)
208 ;;; This would quietly return #f if we extended MEMBER to accept dotted
209 ;;; lists.
210 ;;;
211 ;;; The SRFI discussion record contains more discussion on this topic.
212
213
214 ;;; Constructors
215 ;;;;;;;;;;;;;;;;
216
217 ;;; Occasionally useful as a value to be passed to a fold or other
218 ;;; higher-order procedure.
219 (define (xcons d a) (cons a d))
220
221 ;;;; Recursively copy every cons.
222 ;(define (tree-copy x)
223 ; (let recur ((x x))
224 ; (if (not (pair? x)) x
225 ; (cons (recur (car x)) (recur (cdr x))))))
226
227 ;;; Make a list of length LEN.
228
229 (define make-list
230 (case-lambda
231 ((len) (make-list len #f))
232 ((len elt)
233 (check-arg index? len make-list)
234 (do ((i len (fx- i 1))
235 (ans '() (cons elt ans)))
236 ((fx<=? i 0) ans)))))
237
238
239 ;(define (list . ans) ans) ; R4RS
240
241
242 ;;; Make a list of length LEN. Elt i is (PROC i) for 0 <= i < LEN.
243
244 (define (list-tabulate len proc)
245 (check-arg index? len list-tabulate)
246 (check-arg procedure? proc list-tabulate)
247 (do ((i (fx- len 1) (fx- i 1))
248 (ans '() (cons (proc i) ans)))
249 ((fx<? i 0) ans)))
250
251 ;;; (cons* a1 a2 ... an) = (cons a1 (cons a2 (cons ... an)))
252 ;;; (cons* a1) = a1 (cons* a1 a2 ...) = (cons a1 (cons* a2 ...))
253 ;;;
254 ;;; (cons first (unfold not-pair? car cdr rest values))
255
256 (define cons*
257 (case-lambda
258 ((first) first)
259 ((first second) (cons first second))
260 ((first second third . rest)
261 (cons first
262 (cons second
263 (let recur ((x third) (rest rest))
264 (if (pair? rest)
265 (cons x (recur (car rest) (cdr rest)))
266 x)))))))
267
268 ;;; (unfold not-pair? car cdr lis values)
269
270 (define (list-copy lis)
271 (let recur ((lis lis))
272 (if (pair? lis)
273 (cons (car lis) (recur (cdr lis)))
274 lis)))
275
276 ;;; IOTA count [start step] (start start+step ... start+(count-1)*step)
277
278 (define iota
279 (case-lambda
280 ((count) (iota count 0 1))
281 ((count start) (iota count start 1))
282 ((count start step)
283 (check-arg index? count iota)
284 (check-arg number? start iota)
285 (check-arg number? step iota)
286 (let loop ((cur start) (n 0))
287 (if (fx=? n count)
288 '()
289 (cons cur (loop (fx+ cur step) (fx+ 1 n))))))))
290
291 ;;; I thought these were lovely, but the public at large did not share my
292 ;;; enthusiasm...
293 ;;; :IOTA to (0 ... to-1)
294 ;;; :IOTA from to (from ... to-1)
295 ;;; :IOTA from to step (from from+step ...)
296
297 ;;; IOTA: to (1 ... to)
298 ;;; IOTA: from to (from+1 ... to)
299 ;;; IOTA: from to step (from+step from+2step ...)
300
301 ;(define (%parse-iota-args arg1 rest-args proc)
302 ; (let ((check (lambda (n) (check-arg fixnum? n proc))))
303 ; (check arg1)
304 ; (if (pair? rest-args)
305 ; (let ((arg2 (check (car rest-args)))
306 ; (rest (cdr rest-args)))
307 ; (if (pair? rest)
308 ; (let ((arg3 (check (car rest)))
309 ; (rest (cdr rest)))
310 ; (if (pair? rest) (error "Too many parameters" proc arg1 rest-args)
311 ; (values arg1 arg2 arg3)))
312 ; (values arg1 arg2 1)))
313 ; (values 0 arg1 1))))
314 ;
315 ;(define (iota: arg1 . rest-args)
316 ; (receive (from to step) (%parse-iota-args arg1 rest-args iota:)
317 ; (let* ((numsteps (floor (/ (- to from) step)))
318 ; (last-val (+ from (* step numsteps))))
319 ; (if (< numsteps 0) (error "Negative step count" iota: from to step))
320 ; (do ((steps-left numsteps (- steps-left 1))
321 ; (val last-val (- val step))
322 ; (ans '() (cons val ans)))
323 ; ((<= steps-left 0) ans)))))
324 ;
325 ;
326 ;(define (:iota arg1 . rest-args)
327 ; (receive (from to step) (%parse-iota-args arg1 rest-args :iota)
328 ; (let* ((numsteps (ceiling (/ (- to from) step)))
329 ; (last-val (+ from (* step (- numsteps 1)))))
330 ; (if (< numsteps 0) (error "Negative step count" :iota from to step))
331 ; (do ((steps-left numsteps (- steps-left 1))
332 ; (val last-val (- val step))
333 ; (ans '() (cons val ans)))
334 ; ((<= steps-left 0) ans)))))
335
336
337
338 (define (circular-list val1 . vals)
339 (let ((ans (cons val1 vals)))
340 (set-cdr! (last-pair ans) ans)
341 ans))
342
343 ;;; <proper-list> ::= () ; Empty proper list
344 ;;; | (cons <x> <proper-list>) ; Proper-list pair
345 ;;; Note that this definition rules out circular lists -- and this
346 ;;; function is required to detect this case and return false.
347
348 (define (proper-list? x)
349 (let lp ((x x) (lag x))
350 (if (pair? x)
351 (let ((x (cdr x)))
352 (if (pair? x)
353 (let ((x (cdr x))
354 (lag (cdr lag)))
355 (and (not (eq? x lag)) (lp x lag)))
356 (null? x)))
357 (null? x))))
358
359
360 ;;; A dotted list is a finite list (possibly of length 0) terminated
361 ;;; by a non-nil value. Any non-cons, non-nil value (e.g., "foo" or 5)
362 ;;; is a dotted list of length 0.
363 ;;;
364 ;;; <dotted-list> ::= <non-nil,non-pair> ; Empty dotted list
365 ;;; | (cons <x> <dotted-list>) ; Proper-list pair
366
367 (define (dotted-list? x)
368 (let lp ((x x) (lag x))
369 (if (pair? x)
370 (let ((x (cdr x)))
371 (if (pair? x)
372 (let ((x (cdr x))
373 (lag (cdr lag)))
374 (and (not (eq? x lag)) (lp x lag)))
375 (not (null? x))))
376 (not (null? x)))))
377
378 (define (circular-list? x)
379 (let lp ((x x) (lag x))
380 (and (pair? x)
381 (let ((x (cdr x)))
382 (and (pair? x)
383 (let ((x (cdr x))
384 (lag (cdr lag)))
385 (or (eq? x lag) (lp x lag))))))))
386
387 (define (not-pair? x) (not (pair? x))) ; Inline me.
388
389 ;;; This is a legal definition which is fast and sloppy:
390 ;;; (define null-list? not-pair?)
391 ;;; but we'll provide a more careful one:
392 (define (null-list? l)
393 (cond ((pair? l) #f)
394 ((null? l) #t)
395 (else (error "null-list?: argument out of domain" l))))
396
397
398 (define list=
399 (case-lambda
400 ((elt=) #t)
401 ((elt= list-a) #t)
402 ((elt= list-a list-b)
403 (or (eq? list-a list-b)
404 (let loop ((list-a list-a)
405 (list-b list-b))
406 (if (null-list? list-a)
407 (null-list? list-b)
408 (and (not (null-list? list-b))
409 (elt= (car list-a) (car list-b))
410 (loop (cdr list-a) (cdr list-b)))))))
411 ((elt= list-a list-b list-c . lists)
412 (and (list= elt= list-a list-b)
413 (list= elt= list-b list-c)
414 (or (null? lists)
415 (let loop ((list-a list-c) (lists lists))
416 (let ((list-b (car lists))
417 (others (cdr lists)))
418 (and (list= elt= list-a list-b)
419 (or (null? others)
420 (loop list-b others))))))))))
421
422
423
424 ;;; R4RS, so commented out.
425 ;(define (length x) ; LENGTH may diverge or
426 ; (let lp ((x x) (len 0)) ; raise an error if X is
427 ; (if (pair? x) ; a circular list. This version
428 ; (lp (cdr x) (+ len 1)) ; diverges.
429 ; len)))
430
431 (define (length+ x) ; Returns #f if X is circular.
432 ;; Try 21 times before checking for cicularities
433 (let loop ((x x)
434 (len 0))
435 (if (null? x)
436 len
437 (if (fx>? len 20)
438 ;; Tried 20 times, begin checking for circularities
439 (let lp ((x (cdr x)) (lag x) (len (fx+ len 1)))
440 (if (pair? x)
441 (let ((x (cdr x))
442 (len (fx+ len 1)))
443 (if (pair? x)
444 (let ((x (cdr x))
445 (lag (cdr lag))
446 (len (fx+ len 1)))
447 (and (not (eq? x lag)) (lp x lag len)))
448 len))
449 len))
450 ;; Still not 20 times
451 (loop (cdr x) (fx+ len 1))))))
452
453 (define (zip list1 . more-lists) (apply map list list1 more-lists))
454
455
456 ;;; Selectors
457 ;;;;;;;;;;;;;
458
459 ;;; R4RS non-primitives:
460 ;(define (caar x) (car (car x)))
461 ;(define (cadr x) (car (cdr x)))
462 ;(define (cdar x) (cdr (car x)))
463 ;(define (cddr x) (cdr (cdr x)))
464 ;
465 ;(define (caaar x) (caar (car x)))
466 ;(define (caadr x) (caar (cdr x)))
467 ;(define (cadar x) (cadr (car x)))
468 ;(define (caddr x) (cadr (cdr x)))
469 ;(define (cdaar x) (cdar (car x)))
470 ;(define (cdadr x) (cdar (cdr x)))
471 ;(define (cddar x) (cddr (car x)))
472 ;(define (cdddr x) (cddr (cdr x)))
473 ;
474 ;(define (caaaar x) (caaar (car x)))
475 ;(define (caaadr x) (caaar (cdr x)))
476 ;(define (caadar x) (caadr (car x)))
477 ;(define (caaddr x) (caadr (cdr x)))
478 ;(define (cadaar x) (cadar (car x)))
479 ;(define (cadadr x) (cadar (cdr x)))
480 ;(define (caddar x) (caddr (car x)))
481 ;(define (cadddr x) (caddr (cdr x)))
482 ;(define (cdaaar x) (cdaar (car x)))
483 ;(define (cdaadr x) (cdaar (cdr x)))
484 ;(define (cdadar x) (cdadr (car x)))
485 ;(define (cdaddr x) (cdadr (cdr x)))
486 ;(define (cddaar x) (cddar (car x)))
487 ;(define (cddadr x) (cddar (cdr x)))
488 ;(define (cdddar x) (cdddr (car x)))
489 ;(define (cddddr x) (cdddr (cdr x)))
490
491
492 (define first car)
493 (define second cadr)
494 (define third caddr)
495 (define fourth cadddr)
496 (define (fifth x) (car (cddddr x)))
497 (define (sixth x) (cadr (cddddr x)))
498 (define (seventh x) (caddr (cddddr x)))
499 (define (eighth x) (cadddr (cddddr x)))
500 (define (ninth x) (car (cddddr (cddddr x))))
501 (define (tenth x) (cadr (cddddr (cddddr x))))
502
503 (define (car+cdr pair) (values (car pair) (cdr pair)))
504
505 ;;; take & drop
506
507 (define (take lis k)
508 (check-arg fixnum? k take)
509 (let recur ((lis lis) (k k))
510 (if (zero? k) '()
511 (cons (car lis)
512 (recur (cdr lis) (- k 1))))))
513
514 (define (drop lis k)
515 (check-arg fixnum? k drop)
516 (let iter ((lis lis) (k k))
517 (if (zero? k) lis (iter (cdr lis) (- k 1)))))
518
519 (define (take! lis k)
520 (check-arg fixnum? k take!)
521 (if (zero? k) '()
522 (begin (set-cdr! (drop lis (- k 1)) '())
523 lis)))
524
525 ;;; TAKE-RIGHT and DROP-RIGHT work by getting two pointers into the list,
526 ;;; off by K, then chasing down the list until the lead pointer falls off
527 ;;; the end.
528
529 (define (take-right lis k)
530 (check-arg fixnum? k take-right)
531 (let lp ((lag lis) (lead (drop lis k)))
532 (if (pair? lead)
533 (lp (cdr lag) (cdr lead))
534 lag)))
535
536 (define (drop-right lis k)
537 (check-arg fixnum? k drop-right)
538 (let recur ((lag lis) (lead (drop lis k)))
539 (if (pair? lead)
540 (cons (car lag) (recur (cdr lag) (cdr lead)))
541 '())))
542
543 ;;; In this function, LEAD is actually K+1 ahead of LAG. This lets
544 ;;; us stop LAG one step early, in time to smash its cdr to ().
545 (define (drop-right! lis k)
546 (check-arg fixnum? k drop-right!)
547 (let ((lead (drop lis k)))
548 (if (pair? lead)
549
550 (let lp ((lag lis) (lead (cdr lead))) ; Standard case
551 (if (pair? lead)
552 (lp (cdr lag) (cdr lead))
553 (begin (set-cdr! lag '())
554 lis)))
555
556 '()))) ; Special case dropping everything -- no cons to side-effect.
557
558 ;(define (list-ref lis i) (car (drop lis i))) ; R4RS
559
560 ;;; These use the APL convention, whereby negative indices mean
561 ;;; "from the right." I liked them, but they didn't win over the
562 ;;; SRFI reviewers.
563 ;;; K >= 0: Take and drop K elts from the front of the list.
564 ;;; K <= 0: Take and drop -K elts from the end of the list.
565
566 ;(define (take lis k)
567 ; (check-arg fixnum? k take)
568 ; (if (negative? k)
569 ; (list-tail lis (+ k (length lis)))
570 ; (let recur ((lis lis) (k k))
571 ; (if (zero? k) '()
572 ; (cons (car lis)
573 ; (recur (cdr lis) (- k 1)))))))
574 ;
575 ;(define (drop lis k)
576 ; (check-arg fixnum? k drop)
577 ; (if (negative? k)
578 ; (let recur ((lis lis) (nelts (+ k (length lis))))
579 ; (if (zero? nelts) '()
580 ; (cons (car lis)
581 ; (recur (cdr lis) (- nelts 1)))))
582 ; (list-tail lis k)))
583 ;
584 ;
585 ;(define (take! lis k)
586 ; (check-arg fixnum? k take!)
587 ; (cond ((zero? k) '())
588 ; ((positive? k)
589 ; (set-cdr! (list-tail lis (- k 1)) '())
590 ; lis)
591 ; (else (list-tail lis (+ k (length lis))))))
592 ;
593 ;(define (drop! lis k)
594 ; (check-arg fixnum? k drop!)
595 ; (if (negative? k)
596 ; (let ((nelts (+ k (length lis))))
597 ; (if (zero? nelts) '()
598 ; (begin (set-cdr! (list-tail lis (- nelts 1)) '())
599 ; lis)))
600 ; (list-tail lis k)))
601
602 (define (split-at x k)
603 (check-arg fixnum? k split-at)
604 (let recur ((lis x) (k k))
605 (if (zero? k) (values '() lis)
606 (receive (prefix suffix) (recur (cdr lis) (- k 1))
607 (values (cons (car lis) prefix) suffix)))))
608
609 (define (split-at! x k)
610 (check-arg fixnum? k split-at!)
611 (if (zero? k) (values '() x)
612 (let* ((prev (drop x (- k 1)))
613 (suffix (cdr prev)))
614 (set-cdr! prev '())
615 (values x suffix))))
616
617
618 (define (last lis) (car (last-pair lis)))
619
620 (define (last-pair lis)
621 (check-arg pair? lis last-pair)
622 (let lp ((lis lis))
623 (let ((tail (cdr lis)))
624 (if (pair? tail) (lp tail) lis))))
625
626
627 ;;; Unzippers -- 1 through 5
628 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
629
630 (define (unzip1 lis) (map car lis))
631
632 (define (unzip2 lis)
633 (let recur ((lis lis))
634 (if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle
635 (let ((elt (car lis))) ; dotted lists.
636 (receive (a b) (recur (cdr lis))
637 (values (cons (car elt) a)
638 (cons (cadr elt) b)))))))
639
640 (define (unzip3 lis)
641 (let recur ((lis lis))
642 (if (null-list? lis) (values lis lis lis)
643 (let ((elt (car lis)))
644 (receive (a b c) (recur (cdr lis))
645 (values (cons (car elt) a)
646 (cons (cadr elt) b)
647 (cons (caddr elt) c)))))))
648
649 (define (unzip4 lis)
650 (let recur ((lis lis))
651 (if (null-list? lis) (values lis lis lis lis)
652 (let ((elt (car lis)))
653 (receive (a b c d) (recur (cdr lis))
654 (values (cons (car elt) a)
655 (cons (cadr elt) b)
656 (cons (caddr elt) c)
657 (cons (cadddr elt) d)))))))
658
659 (define (unzip5 lis)
660 (let recur ((lis lis))
661 (if (null-list? lis) (values lis lis lis lis lis)
662 (let ((elt (car lis)))
663 (receive (a b c d e) (recur (cdr lis))
664 (values (cons (car elt) a)
665 (cons (cadr elt) b)
666 (cons (caddr elt) c)
667 (cons (cadddr elt) d)
668 (cons (car (cddddr elt)) e)))))))
669
670
671 ;;; append! append-reverse append-reverse! concatenate concatenate!
672 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
673
674 (define append!
675 (case-lambda
676 (() '())
677 ;; Fast path 1
678 ((lis1) lis1)
679 ;; Fast path 2
680 ((lis1 lis2)
681 (cond
682 ((null? lis2) lis1)
683 ((null? lis1) lis2)
684 (else
685 (set-cdr! (last-pair lis1) lis2)
686 lis1)))
687 ;; N-ary case
688 ((lis1 lis2 lis3 . lists)
689 (let ((append-2! (lambda (lis1 lis2)
690 (set-cdr! (last-pair lis1) lis2)
691 lis1))
692 (lists (delete '() lists)))
693 (if (null? lists)
694 (if (null? lis3)
695 (append! lis1 lis2)
696 (let* ((lis (if (null? lis2) lis3 (append-2! lis2 lis3)))
697 (lis (if (null? lis1) lis (append-2! lis1 lis))))
698 lis))
699 (let* ((lis (let loop ((lis (car lists))
700 (lists (cdr lists)))
701 (if (null? lists) lis
702 (append-2! lis (loop (car lists) (cdr lists))))))
703 (lis (if (null? lis3) lis (append-2! lis3 lis)))
704 (lis (if (null? lis2) lis (append-2! lis2 lis)))
705 (lis (if (null? lis1) lis (append-2! lis1 lis))))
706 lis))))))
707
708 ;;; APPEND is R4RS.
709 ;(define (append . lists)
710 ; (if (pair? lists)
711 ; (let recur ((list1 (car lists)) (lists (cdr lists)))
712 ; (if (pair? lists)
713 ; (let ((tail (recur (car lists) (cdr lists))))
714 ; (fold-right cons tail list1)) ; Append LIST1 & TAIL.
715 ; list1))
716 ; '()))
717
718 ;(define (append-reverse rev-head tail) (fold cons tail rev-head))
719
720 ;(define (append-reverse! rev-head tail)
721 ; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair)
722 ; tail
723 ; rev-head))
724
725 ;;; Hand-inline the FOLD and PAIR-FOLD ops for speed.
726
727 (define (append-reverse rev-head tail)
728 (let lp ((rev-head rev-head) (tail tail))
729 (if (null-list? rev-head) tail
730 (lp (cdr rev-head) (cons (car rev-head) tail)))))
731
732 (define (append-reverse! rev-head tail)
733 (let lp ((rev-head rev-head) (tail tail))
734 (if (null-list? rev-head) tail
735 (let ((next-rev (cdr rev-head)))
736 (set-cdr! rev-head tail)
737 (lp next-rev rev-head)))))
738
739
740 (define (concatenate lists) (reduce-right append '() lists))
741 (define (concatenate! lists) (reduce-right append! '() lists))
742
743 ;;; Fold/map internal utilities
744 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
745 ;;; These little internal utilities are used by the general
746 ;;; fold & mapper funs for the n-ary cases . It'd be nice if they got inlined.
747 ;;; One the other hand, the n-ary cases are painfully inefficient as it is.
748 ;;; An aggressive implementation should simply re-write these functions
749 ;;; for raw efficiency; I have written them for as much clarity, portability,
750 ;;; and simplicity as can be achieved.
751 ;;;
752 ;;; These functions have funky definitions that are precisely tuned to
753 ;;; the needs of the fold/map procs -- for example, to minimize the number
754 ;;; of times the argument lists need to be examined.
755
756 ;;; Return (map cdr lists).
757 ;;; However, if any element of LISTS is empty, just abort and return '().
758 (define (%cdrs lists)
759 (let f ((ls lists))
760 (if (pair? ls)
761 (let ((x (car ls)))
762 (if (null? x)
763 '()
764 (cons (cdr x) (f (cdr ls)))))
765 '())))
766
767 (define (%cars+ lists last-elt) ; (append! (map car lists) (list last-elt))
768 (let recur ((lists lists))
769 (if (pair? lists) (cons (caar lists) (recur (cdr lists))) (list last-elt))))
770
771 ;;; LISTS is a (not very long) non-empty list of lists.
772 ;;; Return two lists: the cars & the cdrs of the lists.
773 ;;; However, if any of the lists is empty, just abort and return [() ()].
774
775 (define (%cars+cdrs lists)
776 (let f ((ls lists))
777 (if (pair? ls)
778 (let ((x (car ls)))
779 (if (null-list? x)
780 (values '() '())
781 (receive (cars cdrs) (f (cdr ls))
782 (values (cons (car x) cars)
783 (cons (cdr x) cdrs)))))
784 (values '() '()))))
785
786 ;;; Like %CARS+CDRS, but we pass in a final elt tacked onto the end of the
787 ;;; cars list. What a hack.
788 (define (%cars+cdrs+ lists cars-final)
789 (let f ((ls lists))
790 (if (pair? ls)
791 (let ((x (car ls)))
792 (if (null-list? x)
793 (values '() '())
794 (receive (cars cdrs) (f (cdr ls))
795 (values (cons (car x) cars)
796 (cons (cdr x) cdrs)))))
797 (values (list cars-final) '()))))
798
799 ;;; Like %CARS+CDRS, but blow up if any list is empty.
800 (define (%cars+cdrs/no-test lists)
801 (let recur ((lists lists))
802 (if (pair? lists)
803 (receive (list other-lists) (car+cdr lists)
804 (receive (a d) (car+cdr list)
805 (receive (cars cdrs) (recur other-lists)
806 (values (cons a cars) (cons d cdrs)))))
807 (values '() '()))))
808
809
810 ;;; count
811 ;;;;;;;;;
812 (define count
813 (case-lambda
814 ;; Fast path
815 ((pred list1)
816 (check-arg procedure? pred count)
817 (let lp ((lis list1) (i 0))
818 (if (null-list? lis) i
819 (lp (cdr lis) (if (pred (car lis)) (fx+ i 1) i)))))
820 ;; N-ary case
821 ((pred list1 . lists)
822 (check-arg procedure? pred count)
823 (let lp ((list1 list1) (lists lists) (i 0))
824 (if (null-list? list1) i
825 (receive (as ds) (%cars+cdrs lists)
826 (if (null? as) i
827 (lp (cdr list1) ds
828 (if (apply pred (car list1) as) (fx+ i 1) i)))))))))
829
830
831 ;;; fold/unfold
832 ;;;;;;;;;;;;;;;
833
834 (define unfold-right
835 (case-lambda
836 ((p f g seed)
837 (unfold-right p f g seed '()))
838 ((p f g seed tail)
839 (check-arg procedure? p unfold-right)
840 (check-arg procedure? f unfold-right)
841 (check-arg procedure? g unfold-right)
842 (let lp ((seed seed) (ans tail))
843 (if (p seed) ans
844 (lp (g seed)
845 (cons (f seed) ans)))))))
846
847
848 (define unfold
849 (case-lambda
850 ((p f g seed)
851 (check-arg procedure? p unfold)
852 (check-arg procedure? f unfold)
853 (check-arg procedure? g unfold)
854 (let recur ((seed seed))
855 (if (p seed) '()
856 (cons (f seed) (recur (g seed))))))
857 ((p f g seed tail-gen)
858 (check-arg procedure? p unfold)
859 (check-arg procedure? f unfold)
860 (check-arg procedure? g unfold)
861 (let recur ((seed seed))
862 (if (p seed) (tail-gen seed)
863 (cons (f seed) (recur (g seed))))))))
864
865
866 (define fold
867 (case-lambda
868 ;; Fast path 1
869 ((kons knil lis1)
870 (check-arg procedure? kons fold)
871 (let lp ((lis lis1) (ans knil))
872 (if (null-list? lis) ans
873 (lp (cdr lis) (kons (car lis) ans)))))
874 ;; Fast path 2
875 ((kons knil lis1 lis2)
876 (check-arg procedure? kons fold)
877 (let lp ((lis1 lis1) (lis2 lis2) (ans knil))
878 (if (or (null-list? lis1) (null-list? lis2))
879 ans
880 (lp (cdr lis1) (cdr lis2) (kons (car lis1) (car lis2) ans)))))
881 ;; N-ary case
882 ((kons knil . lists)
883 (check-arg procedure? kons fold)
884 (let lp ((lists lists) (ans knil)) ; N-ary case
885 (receive (cars+ans cdrs) (%cars+cdrs+ lists ans)
886 (if (null? cars+ans) ans ; Done.
887 (lp cdrs (apply kons cars+ans))))))))
888
889 (define fold-right
890 (case-lambda
891 ;; Fast path 1
892 ((kons knil lis1)
893 (check-arg procedure? kons fold-right)
894 (let recur ((lis lis1))
895 (if (null-list? lis) knil
896 (kons (car lis) (recur (cdr lis))))))
897 ;; Fast path 2
898 ((kons knil lis1 lis2)
899 (check-arg procedure? kons fold-right)
900 (let recur ((lis1 lis1) (lis2 lis2))
901 (if (or (null-list? lis1) (null-list? lis2))
902 knil
903 (kons (car lis1) (car lis2) (recur (cdr lis1) (cdr lis2))))))
904 ;; N-ary case
905 ((kons knil . lists)
906 (check-arg procedure? kons fold-right)
907 (let recur ((lists lists))
908 (let ((cdrs (%cdrs lists)))
909 (if (null? cdrs) knil
910 (apply kons (%cars+ lists (recur cdrs)))))))))
911
912
913 (define pair-fold-right
914 (case-lambda
915 ;; Fast path
916 ((f zero lis1)
917 (check-arg procedure? f pair-fold-right)
918 (let recur ((lis lis1))
919 (if (null-list? lis) zero (f lis (recur (cdr lis))))))
920 ;; N-ary case
921 ((f zero lis1 lis2 . lists)
922 (check-arg procedure? f pair-fold-right)
923 (let recur ((lis1 lis1) (lis2 lis2)
924 (lists lists))
925 (if (or (null-list? lis1) (null-list? lis2))
926 zero
927 (let ((cdrs (%cdrs lists)))
928 (if (null? cdrs) zero
929 (apply f lis1 lis2
930 (append! lists (list (recur (cdr lis1) (cdr lis2) cdrs)))))))))))
931
932 (define pair-fold
933 (case-lambda
934 ;; Fast path
935 ((f zero lis1)
936 (check-arg procedure? f pair-fold)
937 (let lp ((lis lis1) (ans zero))
938 (if (null? lis) ans
939 (let ((tail (cdr lis))) ; Grab the cdr now,
940 (lp tail (f lis ans))))))
941 ;; N-ary case
942 ((f zero lis1 lis2 . lists)
943 (check-arg procedure? f pair-fold)
944 (let lp ((lis1 lis1) (lis2 lis2)
945 (lists lists) (ans zero))
946 (if (or (null-list? lis1) (null-list? lis2))
947 ans
948 (let ((tails (%cdrs lists)))
949 (if (null? tails) ans
950 (lp (cdr lis1) (cdr lis2)
951 tails (apply f lis1 lis2 (append! lists (list ans)))))))))))
952
953
954 ;;; REDUCE and REDUCE-RIGHT only use RIDENTITY in the empty-list case.
955 ;;; These cannot meaningfully be n-ary.
956
957 (define (reduce f ridentity lis)
958 (check-arg procedure? f reduce)
959 (if (null-list? lis) ridentity
960 (fold f (car lis) (cdr lis))))
961
962 (define (reduce-right f ridentity lis)
963 (check-arg procedure? f reduce-right)
964 (if (null-list? lis) ridentity
965 (let recur ((head (car lis)) (lis (cdr lis)))
966 (if (pair? lis)
967 (f head (recur (car lis) (cdr lis)))
968 head))))
969
970
971
972 ;;; Mappers: append-map append-map! pair-for-each map! filter-map map-in-order
973 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
974
975 (define append-map
976 (case-lambda
977 ((f lis1)
978 (really-append-map append-map append f lis1))
979 ((f lis1 lis2)
980 (really-append-map append-map append f lis1 lis2))
981 ((f lis1 lis2 . lists)
982 (really-append-map append-map append f lis1 lis2 lists))))
983
984 (define append-map!
985 (case-lambda
986 ((f lis1)
987 (really-append-map append-map! append! f lis1))
988 ((f lis1 lis2)
989 (really-append-map append-map! append! f lis1 lis2))
990 ((f lis1 lis2 . lists)
991 (really-append-map append-map! append! f lis1 lis2 lists))))
992
993 (define really-append-map
994 (case-lambda
995 ;; Fast path 1
996 ((who appender f lis1)
997 (check-arg procedure? f who)
998 (if (null-list? lis1) '()
999 (let recur ((elt (car lis1)) (rest (cdr lis1)))
1000 (let ((vals (f elt)))
1001 (if (null-list? rest) vals
1002 (appender vals (recur (car rest) (cdr rest))))))))
1003 ;; Fast path 2
1004 ((who appender f lis1 lis2)
1005 (check-arg procedure? f who)
1006 (if (or (null-list? lis1) (null-list? lis2))
1007 '()
1008 (let recur ((lis1 lis1) (lis2 lis2))
1009 (let ((vals (f (car lis1) (car lis2)))
1010 (lis1 (cdr lis1)) (lis2 (cdr lis2)))
1011 (if (or (null-list? lis1) (null-list? lis2))
1012 vals
1013 (appender vals (recur lis1 lis2)))))))
1014 ;; N-ary case
1015 ((who appender f lis1 lis2 lists)
1016 (check-arg procedure? f who)
1017 (if (or (null-list? lis1) (null-list? lis2))
1018 '()
1019 (receive (cars cdrs) (%cars+cdrs lists)
1020 (if (null? cars) '()
1021 (let recur ((lis1 lis1) (lis2 lis2)
1022 (cars cars) (cdrs cdrs))
1023 (let ((vals (apply f (car lis1) (car lis2) cars))
1024 (lis1 (cdr lis1)) (lis2 (cdr lis2)))
1025 (if (or (null-list? lis1) (null-list? lis2))
1026 vals
1027 (receive (cars2 cdrs2) (%cars+cdrs cdrs)
1028 (if (null? cars2) vals
1029 (appender vals (recur lis1 lis2 cars2 cdrs2)))))))))))))
1030
1031
1032 (define pair-for-each
1033 (case-lambda
1034 ;; Fast path
1035 ((proc lis1)
1036 (check-arg procedure? proc pair-for-each)
1037 (let lp ((lis lis1))
1038 (if (not (null-list? lis))
1039 (let ((tail (cdr lis))) ; Grab the cdr now,
1040 (proc lis) ; in case PROC SET-CDR!s LIS.
1041 (lp tail)))))
1042 ;; N-ary case
1043 ((proc lis1 lis2 . lists)
1044 (check-arg procedure? proc pair-for-each)
1045 (let lp ((lis1 lis1) (lis2 lis2)
1046 (lists lists))
1047 (if (and (pair? lis1) (pair? lis2))
1048 (let ((tails (%cdrs lists)))
1049 (if (pair? tails)
1050 (begin (apply proc lis1 lis2 lists)
1051 (lp (cdr lis1) (cdr lis2) tails)))))))))
1052
1053 ;;; We stop when LIS1 runs out, not when any list runs out.
1054 (define map!
1055 (case-lambda
1056 ;; Fast path 1
1057 ((f lis1)
1058 (check-arg procedure? f map!)
1059 (let lp ((lis1 lis1))
1060 (when (not (null-list? lis1))
1061 (set-car! lis1 (f (car lis1)))
1062 (lp (cdr lis1))))
1063 lis1)
1064 ;; Fast path 2
1065 ((f lis1 lis2)
1066 (check-arg procedure? f map!)
1067 (let lp ((lis1 lis1) (lis2 lis2))
1068 (when (not (null-list? lis1))
1069 (set-car! lis1 (f (car lis1) (car lis2)))
1070 (lp (cdr lis1) (cdr lis2))))
1071 lis1)
1072 ;; N-ary case
1073 ((f lis1 lis2 lis3 . lists)
1074 (check-arg procedure? f map!)
1075 (let lp ((lis1 lis1) (lis2 lis2) (lis3 lis3) (lists lists))
1076 (when (not (null-list? lis1))
1077 (receive (heads tails) (%cars+cdrs/no-test lists)
1078 (set-car! lis1 (apply f (car lis1) (car lis2) (car lis3) heads))
1079 (lp (cdr lis1) (cdr lis2) (cdr lis3) tails))))
1080 lis1)))
1081
1082
1083 ;;; Map F across L, and save up all the non-false results.
1084 (define filter-map
1085 (case-lambda
1086 ((f lis1)
1087 (check-arg procedure? f filter-map)
1088 (let recur ((lis lis1))
1089 (if (null-list? lis) '()
1090 (let ((tail (recur (cdr lis))))
1091 (cond ((f (car lis)) => (lambda (x) (cons x tail)))
1092 (else tail))))))
1093 ((f lis1 . lists)
1094 (check-arg procedure? f filter-map)
1095 (let recur ((lis1 lis1) (lists lists))
1096 (if (null-list? lis1) '()
1097 (receive (cars cdrs) (%cars+cdrs lists)
1098 (if (pair? cars)
1099 (cond ((apply f (car lis1) cars)
1100 =>
1101 (lambda (x) (cons x (recur (cdr lis1) cdrs))))
1102 (else (recur (cdr lis1) cdrs))) ; Tail call in this arm.
1103 '())))))))
1104
1105
1106 ;;; Map F across lists, guaranteeing to go left-to-right.
1107 ;;; NOTE: Some implementations of R5RS MAP are compliant with this spec;
1108 ;;; in which case this procedure may simply be defined as a synonym for MAP.
1109
1110 (define map-in-order
1111 (case-lambda
1112 ((f lis1)
1113 (check-arg procedure? f map-in-order)
1114 (let recur ((lis lis1))
1115 (if (null-list? lis)
1116 lis
1117 (let ((tail (cdr lis))
1118 (x (f (car lis)))) ; Do head first,
1119 (cons x (recur tail)))))) ; then tail
1120 ((f lis1 lis2)
1121 (check-arg procedure? f map-in-order)
1122 (let recur ((lis1 lis1) (lis2 lis2))
1123 (if (and (pair? lis1) (pair? lis2))
1124 (let ((x (f (car lis1) (car lis2)))) ; Do head first,
1125 (cons x (recur (cdr lis1) (cdr lis2)))) ; then tail.
1126 '())))
1127 ((f lis1 lis2 . lists)
1128 (check-arg procedure? f map-in-order)
1129 (let recur ((lis1 lis1) (lis2 lis2) (lists lists))
1130 (receive (cars cdrs) (%cars+cdrs lists)
1131 (if (and (pair? lis1) (pair? lis2) (pair? cars))
1132 (let ((x (apply f (car lis1) (car lis2) cars))) ; Do head first,
1133 (cons x (recur (cdr lis1) (cdr lis2) cdrs))) ; then tail.
1134 '()))))))
1135
1136
1137 ;;; We extend MAP to handle arguments of unequal length.
1138 (define map map-in-order)
1139
1140 ;;; Contributed by Michael Sperber since it was missing from the
1141 ;;; reference implementation.
1142 (define for-each
1143 (case-lambda
1144 ;; Fast path 1
1145 ((f lis1)
1146 (r6rs:for-each f lis1))
1147 ;; Fast path 2
1148 ((f lis1 lis2)
1149 (check-arg procedure? f for-each)
1150 (let recur ((lis1 lis1) (lis2 lis2))
1151 (unless (or (null-list? lis1) (null-list? lis2))
1152 (f (car lis1) (car lis2))
1153 (recur (cdr lis1) (cdr lis2)))))
1154 ;; N-ary case
1155 ((f lis1 lis2 . lists)
1156 (check-arg procedure? f for-each)
1157 (let recur ((lis1 lis1) (lis2 lis2) (lists lists))
1158 (unless (or (null-list? lis1) (null-list? lis2))
1159 (receive (cars cdrs) (%cars+cdrs lists)
1160 (when (pair? cars)
1161 (apply f (car lis1) (car lis2) cars) ; Do head first,
1162 (recur (cdr lis1) (cdr lis2) cdrs)))))))) ; then tail.
1163
1164
1165 ;;; filter, remove, partition
1166 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1167 ;;; FILTER, REMOVE, PARTITION and their destructive counterparts do not
1168 ;;; disorder the elements of their argument.
1169
1170 ;; This FILTER shares the longest tail of L that has no deleted elements.
1171 ;; If Scheme had multi-continuation calls, they could be made more efficient.
1172
1173 (define (filter pred lis) ; Sleazing with EQ? makes this
1174 (check-arg procedure? pred filter) ; one faster.
1175 (let recur ((lis lis))
1176 (if (null-list? lis) lis ; Use NOT-PAIR? to handle dotted lists.
1177 (let ((head (car lis))
1178 (tail (cdr lis)))
1179 (if (pred head)
1180 (let ((new-tail (recur tail))) ; Replicate the RECUR call so
1181 (if (eq? tail new-tail) lis
1182 (cons head new-tail)))
1183 (recur tail)))))) ; this one can be a tail call.
1184
1185
1186 ;;; Another version that shares longest tail.
1187 ;(define (filter pred lis)
1188 ; (receive (ans no-del?)
1189 ; ;; (recur l) returns L with (pred x) values filtered.
1190 ; ;; It also returns a flag NO-DEL? if the returned value
1191 ; ;; is EQ? to L, i.e. if it didn't have to delete anything.
1192 ; (let recur ((l l))
1193 ; (if (null-list? l) (values l #t)
1194 ; (let ((x (car l))
1195 ; (tl (cdr l)))
1196 ; (if (pred x)
1197 ; (receive (ans no-del?) (recur tl)
1198 ; (if no-del?
1199 ; (values l #t)
1200 ; (values (cons x ans) #f)))
1201 ; (receive (ans no-del?) (recur tl) ; Delete X.
1202 ; (values ans #f))))))
1203 ; ans))
1204
1205
1206
1207 ;(define (filter! pred lis) ; Things are much simpler
1208 ; (let recur ((lis lis)) ; if you are willing to
1209 ; (if (pair? lis) ; push N stack frames & do N
1210 ; (cond ((pred (car lis)) ; SET-CDR! writes, where N is
1211 ; (set-cdr! lis (recur (cdr lis))); the length of the answer.
1212 ; lis)
1213 ; (else (recur (cdr lis))))
1214 ; lis)))
1215
1216
1217 ;;; This implementation of FILTER!
1218 ;;; - doesn't cons, and uses no stack;
1219 ;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
1220 ;;; usually expensive on modern machines, and can be extremely expensive on
1221 ;;; modern Schemes (e.g., ones that have generational GC's).
1222 ;;; It just zips down contiguous runs of in and out elts in LIS doing the
1223 ;;; minimal number of SET-CDR!s to splice the tail of one run of ins to the
1224 ;;; beginning of the next.
1225
1226 (define (filter! pred lis)
1227 (check-arg procedure? pred filter!)
1228 (let lp ((ans lis))
1229 (cond ((null-list? ans) ans) ; Scan looking for
1230 ((not (pred (car ans))) (lp (cdr ans))) ; first cons of result.
1231
1232 ;; ANS is the eventual answer.
1233 ;; SCAN-IN: (CDR PREV) = LIS and (CAR PREV) satisfies PRED.
1234 ;; Scan over a contiguous segment of the list that
1235 ;; satisfies PRED.
1236 ;; SCAN-OUT: (CAR PREV) satisfies PRED. Scan over a contiguous
1237 ;; segment of the list that *doesn't* satisfy PRED.
1238 ;; When the segment ends, patch in a link from PREV
1239 ;; to the start of the next good segment, and jump to
1240 ;; SCAN-IN.
1241 (else (letrec ((scan-in (lambda (prev lis)
1242 (if (pair? lis)
1243 (if (pred (car lis))
1244 (scan-in lis (cdr lis))
1245 (scan-out prev (cdr lis))))))
1246 (scan-out (lambda (prev lis)
1247 (let lp ((lis lis))
1248 (if (pair? lis)
1249 (if (pred (car lis))
1250 (begin (set-cdr! prev lis)
1251 (scan-in lis (cdr lis)))
1252 (lp (cdr lis)))
1253 (set-cdr! prev lis))))))
1254 (scan-in ans (cdr ans))
1255 ans)))))
1256
1257
1258
1259 ;;; Answers share common tail with LIS where possible;
1260 ;;; the technique is slightly subtle.
1261
1262 (define (partition pred lis)
1263 (check-arg procedure? pred partition)
1264 (let recur ((lis lis))
1265 (if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle dotted lists.
1266 (let ((elt (car lis))
1267 (tail (cdr lis)))
1268 (receive (in out) (recur tail)
1269 (if (pred elt)
1270 (values (if (pair? out) (cons elt in) lis) out)
1271 (values in (if (pair? in) (cons elt out) lis))))))))
1272
1273
1274
1275 ;(define (partition! pred lis) ; Things are much simpler
1276 ; (let recur ((lis lis)) ; if you are willing to
1277 ; (if (null-list? lis) (values lis lis) ; push N stack frames & do N
1278 ; (let ((elt (car lis))) ; SET-CDR! writes, where N is
1279 ; (receive (in out) (recur (cdr lis)) ; the length of LIS.
1280 ; (cond ((pred elt)
1281 ; (set-cdr! lis in)
1282 ; (values lis out))
1283 ; (else (set-cdr! lis out)
1284 ; (values in lis))))))))
1285
1286
1287 ;;; This implementation of PARTITION!
1288 ;;; - doesn't cons, and uses no stack;
1289 ;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
1290 ;;; usually expensive on modern machines, and can be extremely expensive on
1291 ;;; modern Schemes (e.g., ones that have generational GC's).
1292 ;;; It just zips down contiguous runs of in and out elts in LIS doing the
1293 ;;; minimal number of SET-CDR!s to splice these runs together into the result
1294 ;;; lists.
1295
1296 (define (partition! pred lis)
1297 (check-arg procedure? pred partition!)
1298 (if (null-list? lis) (values lis lis)
1299
1300 ;; This pair of loops zips down contiguous in & out runs of the
1301 ;; list, splicing the runs together. The invariants are
1302 ;; SCAN-IN: (cdr in-prev) = LIS.
1303 ;; SCAN-OUT: (cdr out-prev) = LIS.
1304 (letrec ((scan-in (lambda (in-prev out-prev lis)
1305 (let lp ((in-prev in-prev) (lis lis))
1306 (if (pair? lis)
1307 (if (pred (car lis))
1308 (lp lis (cdr lis))
1309 (begin (set-cdr! out-prev lis)
1310 (scan-out in-prev lis (cdr lis))))
1311 (set-cdr! out-prev lis))))) ; Done.
1312
1313 (scan-out (lambda (in-prev out-prev lis)
1314 (let lp ((out-prev out-prev) (lis lis))
1315 (if (pair? lis)
1316 (if (pred (car lis))
1317 (begin (set-cdr! in-prev lis)
1318 (scan-in lis out-prev (cdr lis)))
1319 (lp lis (cdr lis)))
1320 (set-cdr! in-prev lis)))))) ; Done.
1321
1322 ;; Crank up the scan&splice loops.
1323 (if (pred (car lis))
1324 ;; LIS begins in-list. Search for out-list's first pair.
1325 (let lp ((prev-l lis) (l (cdr lis)))
1326 (cond ((not (pair? l)) (values lis l))
1327 ((pred (car l)) (lp l (cdr l)))
1328 (else (scan-out prev-l l (cdr l))
1329 (values lis l)))) ; Done.
1330
1331 ;; LIS begins out-list. Search for in-list's first pair.
1332 (let lp ((prev-l lis) (l (cdr lis)))
1333 (cond ((not (pair? l)) (values l lis))
1334 ((pred (car l))
1335 (scan-in l prev-l (cdr l))
1336 (values l lis)) ; Done.
1337 (else (lp l (cdr l)))))))))
1338
1339 ;; (define (remove pred l) (filter (lambda (x) (not (pred x))) l))
1340 ;; (define (remove! pred l) (filter! (lambda (x) (not (pred x))) l))
1341
1342 ;; Avoid allocating a procedure
1343 ;; Just a copy of filter with (pred head) <-> (not (pred head))
1344 (define (remove pred lis)
1345 (check-arg procedure? pred remove)
1346 (let recur ((lis lis))
1347 (if (null-list? lis) lis
1348 (let ((head (car lis))
1349 (tail (cdr lis)))
1350 (if (not (pred head))
1351 (let ((new-tail (recur tail)))
1352 (if (eq? tail new-tail) lis
1353 (cons head new-tail)))
1354 (recur tail))))))
1355
1356 ;; Avoid allocating a procedure
1357 ;; Just a copy of filter! with (pred head) <-> (not (pred head))
1358 (define (remove! pred lis)
1359 (check-arg procedure? pred remove!)
1360 (let lp ((ans lis))
1361 (cond ((null-list? ans) ans) ; Scan looking for
1362 ((pred (car ans)) (lp (cdr ans))) ; first cons of result.
1363
1364 (else (letrec ((scan-in (lambda (prev lis)
1365 (if (pair? lis)
1366 (if (not (pred (car lis)))
1367 (scan-in lis (cdr lis))
1368 (scan-out prev (cdr lis))))))
1369 (scan-out (lambda (prev lis)
1370 (let lp ((lis lis))
1371 (if (pair? lis)
1372 (if (not (pred (car lis)))
1373 (begin (set-cdr! prev lis)
1374 (scan-in lis (cdr lis)))
1375 (lp (cdr lis)))
1376 (set-cdr! prev lis))))))
1377 (scan-in ans (cdr ans))
1378 ans)))))
1379
1380
1381
1382 ;;; Here's the taxonomy for the DELETE/ASSOC/MEMBER functions.
1383 ;;; (I don't actually think these are the world's most important
1384 ;;; functions -- the procedural FILTER/REMOVE/FIND/FIND-TAIL variants
1385 ;;; are far more general.)
1386 ;;;
1387 ;;; Function Action
1388 ;;; ---------------------------------------------------------------------------
1389 ;;; remove pred lis Delete by general predicate
1390 ;;; delete x lis [=] Delete by element comparison
1391 ;;;
1392 ;;; find pred lis Search by general predicate
1393 ;;; find-tail pred lis Search by general predicate
1394 ;;; member x lis [=] Search by element comparison
1395 ;;;
1396 ;;; assoc key lis [=] Search alist by key comparison
1397 ;;; alist-delete key alist [=] Alist-delete by key comparison
1398
1399 (define delete
1400 (case-lambda
1401 ((x lis)
1402 (delete x lis equal?))
1403 ((x lis elt=)
1404 (let recur ((lis lis))
1405 (if (null-list? lis) lis
1406 (let ((head (car lis))
1407 (tail (cdr lis)))
1408 (if (not (elt= x head))
1409 (let ((new-tail (recur tail)))
1410 (if (eq? tail new-tail) lis
1411 (cons head new-tail)))
1412 (recur tail))))))))
1413
1414 (define delete!
1415 (case-lambda
1416 ((x lis)
1417 (delete! x lis equal?))
1418 ((x lis elt=)
1419 (let lp ((ans lis))
1420 (cond ((null-list? ans) ans) ; Scan looking for
1421 ((elt= x (car ans)) (lp (cdr ans))) ; first cons of result.
1422
1423 (else (letrec ((scan-in (lambda (prev lis)
1424 (if (pair? lis)
1425 (if (not (elt= x (car lis)))
1426 (scan-in lis (cdr lis))
1427 (scan-out prev (cdr lis))))))
1428 (scan-out (lambda (prev lis)
1429 (let lp ((lis lis))
1430 (if (pair? lis)
1431 (if (not (elt= x (car lis)))
1432 (begin (set-cdr! prev lis)
1433 (scan-in lis (cdr lis)))
1434 (lp (cdr lis)))
1435 (set-cdr! prev lis))))))
1436 (scan-in ans (cdr ans))
1437 ans)))))))
1438
1439 ;;; Extended from R4RS to take an optional comparison argument.
1440 (define member
1441 (case-lambda
1442 ((x lis)
1443 (r6rs:member x lis))
1444 ((x lis elt=)
1445 (let lp ((lis lis))
1446 (and (not (null-list? lis))
1447 (if (elt= x (car lis)) lis
1448 (lp (cdr lis))))))))
1449
1450 ;;; R4RS, hence we don't bother to define.
1451 ;;; The MEMBER and then FIND-TAIL call should definitely
1452 ;;; be inlined for MEMQ & MEMV.
1453 ;(define (memq x lis) (member x lis eq?))
1454 ;(define (memv x lis) (member x lis eqv?))
1455
1456
1457 ;;; right-duplicate deletion
1458 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1459 ;;; delete-duplicates delete-duplicates!
1460 ;;;
1461 ;;; Beware -- these are N^2 algorithms. To efficiently remove duplicates
1462 ;;; in long lists, sort the list to bring duplicates together, then use a
1463 ;;; linear-time algorithm to kill the dups. Or use an algorithm based on
1464 ;;; element-marking. The former gives you O(n lg n), the latter is linear.
1465
1466 (define delete-duplicates
1467 (case-lambda
1468 ((lis)
1469 (delete-duplicates lis equal?))
1470 ((lis elt=)
1471 (check-arg procedure? elt= delete-duplicates)
1472 (let recur ((lis lis))
1473 (if (null-list? lis) lis
1474 (let* ((x (car lis))
1475 (tail (cdr lis))
1476 (new-tail (recur (delete x tail elt=))))
1477 (if (eq? tail new-tail) lis (cons x new-tail))))))))
1478
1479 (define delete-duplicates!
1480 (case-lambda
1481 ((lis)
1482 (delete-duplicates! lis equal?))
1483 ((lis elt=)
1484 (check-arg procedure? elt= delete-duplicates!)
1485 (let recur ((lis lis))
1486 (if (null-list? lis) lis
1487 (let* ((x (car lis))
1488 (tail (cdr lis))
1489 (new-tail (recur (delete! x tail elt=))))
1490 (if (not (eq? tail new-tail))
1491 (set-cdr! lis new-tail))
1492 lis))))))
1493
1494
1495 ;;; alist stuff
1496 ;;;;;;;;;;;;;;;
1497
1498 ;;; Extended from R4RS to take an optional comparison argument.
1499 (define assoc
1500 (case-lambda
1501 ((x lis)
1502 (r6rs:assoc x lis))
1503 ((x lis elt=)
1504 (let loop ((lis lis))
1505 (if (pair? lis)
1506 (let ((entry (car lis)))
1507 (if (elt= x (car entry)) entry
1508 (loop (cdr lis))))
1509 #f)))))
1510
1511 (define (alist-cons key datum alist) (cons (cons key datum) alist))
1512
1513 (define (alist-copy alist)
1514 (map (lambda (elt) (cons (car elt) (cdr elt)))
1515 alist))
1516
1517 (define alist-delete
1518 (case-lambda
1519 ((key alist)
1520 (remove (lambda (elt) (equal? key (car elt))) alist))
1521 ((key alist elt=)
1522 (remove (lambda (elt) (elt= key (car elt))) alist))))
1523
1524 (define alist-delete!
1525 (case-lambda
1526 ((key alist)
1527 (remove! (lambda (elt) (equal? key (car elt))) alist))
1528 ((key alist elt=)
1529 (remove! (lambda (elt) (elt= key (car elt))) alist))))
1530
1531
1532 ;;; find find-tail take-while drop-while span break any every list-index
1533 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1534
1535 (define (find pred lis)
1536 (check-arg procedure? pred find)
1537 (let loop ((lis lis))
1538 (if (pair? lis)
1539 (let ((head (car lis)))
1540 (if (pred head) head
1541 (loop (cdr lis))))
1542 #f)))
1543
1544 (define (find-tail pred lis)
1545 (check-arg procedure? pred find-tail)
1546 (let lp ((lis lis))
1547 (and (not (null-list? lis))
1548 (if (pred (car lis)) lis
1549 (lp (cdr lis))))))
1550
1551 (define (take-while pred lis)
1552 (check-arg procedure? pred take-while)
1553 (let recur ((lis lis))
1554 (if (null-list? lis) '()
1555 (let ((x (car lis)))
1556 (if (pred x)
1557 (cons x (recur (cdr lis)))
1558 '())))))
1559
1560 (define (drop-while pred lis)
1561 (check-arg procedure? pred drop-while)
1562 (let lp ((lis lis))
1563 (if (null-list? lis) '()
1564 (if (pred (car lis))
1565 (lp (cdr lis))
1566 lis))))
1567
1568 (define (take-while! pred lis)
1569 (check-arg procedure? pred take-while!)
1570 (if (or (null-list? lis) (not (pred (car lis)))) '()
1571 (begin (let lp ((prev lis) (rest (cdr lis)))
1572 (if (pair? rest)
1573 (let ((x (car rest)))
1574 (if (pred x) (lp rest (cdr rest))
1575 (set-cdr! prev '())))))
1576 lis)))
1577
1578 (define (span pred lis)
1579 (check-arg procedure? pred span)
1580 (let recur ((lis lis))
1581 (if (null-list? lis) (values '() '())
1582 (let ((x (car lis)))
1583 (if (pred x)
1584 (receive (prefix suffix) (recur (cdr lis))
1585 (values (cons x prefix) suffix))
1586 (values '() lis))))))
1587
1588 (define (span! pred lis)
1589 (check-arg procedure? pred span!)
1590 (if (or (null-list? lis) (not (pred (car lis)))) (values '() lis)
1591 (let ((suffix (let lp ((prev lis) (rest (cdr lis)))
1592 (if (null-list? rest) rest
1593 (let ((x (car rest)))
1594 (if (pred x) (lp rest (cdr rest))
1595 (begin (set-cdr! prev '())
1596 rest)))))))
1597 (values lis suffix))))
1598
1599
1600 ;; (define (break pred lis) (span (lambda (x) (not (pred x))) lis))
1601 ;; (define (break! pred lis) (span! (lambda (x) (not (pred x))) lis))
1602
1603 ;; span with pred -> not pred
1604 (define (break pred lis)
1605 (check-arg procedure? pred break)
1606 (let recur ((lis lis))
1607 (if (null-list? lis) (values '() '())
1608 (let ((x (car lis)))
1609 (if (not (pred x))
1610 (receive (prefix suffix) (recur (cdr lis))
1611 (values (cons x prefix) suffix))
1612 (values '() lis))))))
1613
1614 ;; span! with pred <-> not pred
1615 (define (break! pred lis)
1616 (check-arg procedure? pred break!)
1617 (if (or (null-list? lis) (pred (car lis))) (values '() lis)
1618 (let ((suffix (let lp ((prev lis) (rest (cdr lis)))
1619 (if (null-list? rest) rest
1620 (let ((x (car rest)))
1621 (if (not (pred x)) (lp rest (cdr rest))
1622 (begin (set-cdr! prev '())
1623 rest)))))))
1624 (values lis suffix))))
1625
1626 (define any
1627 (case-lambda
1628 ;; Fast path 1
1629 ((pred lis1)
1630 (check-arg procedure? pred any)
1631 (and (not (null-list? lis1))
1632 (let loop ((head (car lis1)) (tail (cdr lis1)))
1633 (if (null-list? tail)
1634 (pred head) ; Last PRED app is tail call.
1635 (or (pred head) (loop (car tail) (cdr tail)))))))
1636 ;; Fast path 2
1637 ((pred lis1 lis2)
1638 (check-arg procedure? pred any)
1639 (and (not (null-list? lis1)) (not (null-list? lis2))
1640 (let loop ((head1 (car lis1)) (tail1 (cdr lis1))
1641 (head2 (car lis2)) (tail2 (cdr lis2)))
1642 (if (or (null-list? tail1) (null-list? tail2))
1643 (pred head1 head2) ; Last PRED app is tail call.
1644 (or (pred head1 head2)
1645 (loop (car tail1) (cdr tail1)
1646 (car tail2) (cdr tail2)))))))
1647 ;; N-ary case
1648 ((pred lis1 lis2 . lists)
1649 (check-arg procedure? pred any)
1650 (and (not (null-list? lis1)) (not (null-list? lis2))
1651 (receive (heads tails) (%cars+cdrs lists)
1652 (and (pair? heads)
1653 (let loop ((head1 (car lis1)) (tail1 (cdr lis1))
1654 (head2 (car lis2)) (tail2 (cdr lis2))
1655 (heads heads) (tails tails))
1656 (if (or (null-list? tail1) (null-list? tail2))
1657 (apply pred head1 head2 heads)
1658 ; Last PRED app is tail call.
1659 (receive (next-heads next-tails) (%cars+cdrs tails)
1660 (if (null? next-tails)
1661 (apply pred head1 head2 heads)
1662 ; Last PRED app is tail call.
1663 (or (apply pred head1 head2 heads)
1664 (loop (car tail1) (cdr tail1)
1665 (car tail2) (cdr tail2)
1666 next-heads next-tails))))))))))))
1667
1668
1669 ;;(define (every pred list) ; Simple definition.
1670 ;; (let lp ((list list)) ; Doesn't return the last PRED value.
1671 ;; (or (not (pair? list))
1672 ;; (and (pred (car list))
1673 ;; (lp (cdr list))))))
1674
1675 (define every
1676 (case-lambda
1677 ;; Fast path 1
1678 ((pred lis1)
1679 (check-arg procedure? pred every)
1680 (or (null-list? lis1)
1681 (let loop ((head (car lis1)) (tail (cdr lis1)))
1682 (if (null-list? tail)
1683 (pred head) ; Last PRED app is tail call.
1684 (and (pred head) (loop (car tail) (cdr tail)))))))
1685 ;; Fast path 2
1686 ((pred lis1 lis2)
1687 (check-arg procedure? pred every)
1688 (or (null-list? lis1) (null-list? lis2)
1689 (let loop ((head1 (car lis1)) (tail1 (cdr lis1))
1690 (head2 (car lis2)) (tail2 (cdr lis2)))
1691 (if (or (null-list? tail1) (null-list? tail2))
1692 (pred head1 head2) ; Last PRED app is tail call.
1693 (and (pred head1 head2)
1694 (loop (car tail1) (cdr tail1)
1695 (car tail2) (cdr tail2)))))))
1696 ;; N-ary case
1697 ((pred lis1 lis2 . lists)
1698 (check-arg procedure? pred every)
1699 (or (null-list? lis1) (null-list? lis2)
1700 (receive (heads tails) (%cars+cdrs lists)
1701 (or (not (pair? heads))
1702 (let loop ((head1 (car lis1)) (tail1 (cdr lis1))
1703 (head2 (car lis2)) (tail2 (cdr lis2))
1704 (heads heads) (tails tails))
1705 (if (or (null-list? tail1) (null-list? tail2))
1706 (apply pred head1 head2 heads)
1707 ; Last PRED app is tail call.
1708 (receive (next-heads next-tails) (%cars+cdrs tails)
1709 (if (null? next-tails)
1710 (apply pred head1 head2 heads)
1711 ; Last PRED app is tail call.
1712 (and (apply pred head1 head2 heads)
1713 (loop (car tail1) (cdr tail1)
1714 (car tail2) (cdr tail2)
1715 next-heads next-tails))))))))))))
1716
1717 (define list-index
1718 (case-lambda
1719 ;; Fast path 1
1720 ((pred lis1)
1721 (check-arg procedure? pred list-index)
1722 (let loop ((lis lis1)
1723 (n 0))
1724 (and (not (null-list? lis))
1725 (if (pred (car lis)) n (loop (cdr lis) (fx+ n 1))))))
1726 ;; Fast path 2
1727 ((pred lis1 lis2)
1728 (check-arg procedure? pred list-index)
1729 (let loop ((lis1 lis1)
1730 (lis2 lis2)
1731 (n 0))
1732 (and (not (or (null-list? lis1) (null-list? lis2)))
1733 (if (pred (car lis1) (car lis2))
1734 n
1735 (loop (cdr lis1) (cdr lis2) (fx+ n 1))))))
1736 ;; N-ary case
1737 ((pred lis1 lis2 lis3 . lists)
1738 (check-arg procedure? pred list-index)
1739 (let loop ((lis1 lis1) (lis2 lis2) (lis3 lis3)
1740 (lists lists)
1741 (n 0))
1742 (and (not (or (null-list? lis1) (null-list? lis2) (null-list? lis3)))
1743 (receive (heads tails) (%cars+cdrs lists)
1744 (and (not (null? heads))
1745 (if (apply pred (car lis1) (car lis2) (car lis3) heads)
1746 n
1747 (loop (cdr lis1) (cdr lis2) (cdr lis3) tails
1748 (fx+ n 1))))))))))
1749
1750 ;;; Reverse
1751 ;;;;;;;;;;;
1752
1753 ;R4RS, so not defined here.
1754 ;(define (reverse lis) (fold cons '() lis))
1755
1756 ;(define (reverse! lis)
1757 ; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair) '() lis))
1758
1759 (define (reverse! lis)
1760 (let lp ((lis lis) (ans '()))
1761 (if (null-list? lis) ans
1762 (let ((tail (cdr lis)))
1763 (set-cdr! lis ans)
1764 (lp tail lis)))))
1765
1766 ;;; Lists-as-sets
1767 ;;;;;;;;;;;;;;;;;
1768
1769 ;;; This is carefully tuned code; do not modify casually.
1770 ;;; - It is careful to share storage when possible;
1771 ;;; - Side-effecting code tries not to perform redundant writes.
1772 ;;; - It tries to avoid linear-time scans in special cases where constant-time
1773 ;;; computations can be performed.
1774 ;;; - It relies on similar properties from the other list-lib procs it calls.
1775 ;;; For example, it uses the fact that the implementations of MEMBER and
1776 ;;; FILTER in this source code share longest common tails between args
1777 ;;; and results to get structure sharing in the lset procedures.
1778
1779 (define (%lset2<= = lis1 lis2) (every (lambda (x) (member x lis2 =)) lis1))
1780
1781 (define lset<=
1782 (case-lambda
1783 ((=) (check-arg procedure? = lset<=) #t)
1784 ((= lis1) (check-arg procedure? = lset<=) #t)
1785 ((= lis1 lis2)
1786 (check-arg procedure? = lset<=)
1787 (or (eq? lis1 lis2) (%lset2<= = lis1 lis2)))
1788 ((= lis1 lis2 lis3 . lists)
1789 (check-arg procedure? = lset<=)
1790 (and (or (eq? lis1 lis2) (%lset2<= = lis1 lis2))
1791 (or (eq? lis2 lis3) (%lset2<= = lis2 lis3))
1792 (or (null? lists)
1793 (let loop ((lis1 lis3)
1794 (lis2 (car lists))
1795 (lists (cdr lists)))
1796 (and (or (eq? lis1 lis2) (%lset2<= = lis1 lis2))
1797 (or (null? lists)
1798 (loop lis2 (car lists) (cdr lists))))))))))
1799
1800 (define lset=
1801 (case-lambda
1802 ((=) (check-arg procedure? = lset=) #t)
1803 ((= lis1) (check-arg procedure? = lset=) #t)
1804 ((= lis1 lis2)
1805 (check-arg procedure? = lset=)
1806 (or (eq? lis1 lis2)
1807 (and (%lset2<= = lis1 lis2) (%lset2<= = lis2 lis1))))
1808 ((= lis1 lis2 lis3 . lists)
1809 (check-arg procedure? = lset=)
1810 (and (or (eq? lis1 lis2)
1811 (and (%lset2<= = lis1 lis2) (%lset2<= = lis2 lis1)))
1812 (or (eq? lis2 lis3)
1813 (and (%lset2<= = lis2 lis3) (%lset2<= = lis3 lis2)))
1814 (or (null? lists)
1815 (let loop ((lis1 lis3)
1816 (lis2 (car lists))
1817 (lists (cdr lists)))
1818 (and (or (eq? lis1 lis2)
1819 (and (%lset2<= = lis1 lis2) (%lset2<= = lis2 lis1)))
1820 (or (null? lists)
1821 (loop lis2 (car lists) (cdr lists))))))))))
1822
1823
1824 (define lset-adjoin
1825 (case-lambda
1826 ((= lis) lis)
1827 ((= lis elt)
1828 (check-arg procedure? = lset-adjoin)
1829 (if (member elt lis) lis (cons elt lis)))
1830 ((= lis elt1 elt2)
1831 (check-arg procedure? = lset-adjoin)
1832 (let* ((lis (if (member elt1 lis) lis (cons elt1 lis)))
1833 (lis (if (member elt2 lis) lis (cons elt2 lis))))
1834 lis))
1835 ((= lis elt1 elt2 elt3 . elts)
1836 (check-arg procedure? = lset-adjoin)
1837 (let* ((lis (if (member elt1 lis) lis (cons elt1 lis)))
1838 (lis (if (member elt2 lis) lis (cons elt2 lis)))
1839 (lis (if (member elt3 lis) lis (cons elt3 lis))))
1840 (if (null? elts) lis
1841 (fold (lambda (elt ans) (if (member elt ans =) ans (cons elt ans)))
1842 lis elts))))))
1843
1844
1845 (define lset-union
1846 (let ((lset-union-2
1847 (lambda (= lis1 lis2)
1848 (cond ((null? lis1) lis2) ; Don't copy any lists
1849 ((null? lis2) lis1) ; if we don't have to.
1850 ((eq? lis1 lis2) lis1)
1851 (else
1852 (fold (lambda (elt ans)
1853 (if (member elt ans =)
1854 ans
1855 (cons elt ans)))
1856 lis1 lis2))))))
1857 (case-lambda
1858 ((=) (check-arg procedure? = lset-union) '())
1859 ((= lis1) (check-arg procedure? = lset-union) lis1)
1860 ((= lis1 lis2)
1861 (check-arg procedure? = lset-union)
1862 (lset-union-2 = lis1 lis2))
1863 ((= lis1 lis2 lis3 . lists)
1864 (check-arg procedure? = lset-union)
1865 (let* ((lis (lset-union-2 = lis1 lis2))
1866 (lis (lset-union-2 = lis lis3)))
1867 (if (null? lists) lis
1868 (fold (lambda (lis2 lis1) (lset-union-2 = lis1 lis2))
1869 lis lists)))))))
1870
1871 (define lset-union!
1872 (let ((lset-union-2!
1873 (lambda (= lis1 lis2)
1874 (cond ((null? lis1) lis2) ; Don't copy any lists
1875 ((null? lis2) lis1) ; if we don't have to.
1876 ((eq? lis1 lis2) lis1)
1877 (else
1878 (pair-fold (lambda (pair ans)
1879 (let ((elt (car pair)))
1880 (if (member elt ans =)
1881 ans
1882 (begin (set-cdr! pair ans) pair))))
1883 lis1 lis2))))))
1884 (case-lambda
1885 ((=)
1886 (check-arg procedure? = lset-union!)
1887 '())
1888 ((= lis1) (check-arg procedure? = lset-union!) lis1)
1889 ((= lis1 lis2) ; Splice new elts of LIS1 onto the front of LIS2.
1890 (check-arg procedure? = lset-union!)
1891 (lset-union-2! = lis1 lis2))
1892 ((= lis1 lis2 lis3 . lists)
1893 (check-arg procedure? = lset-union!)
1894 (let* ((lis (lset-union-2! = lis1 lis2))
1895 (lis (lset-union-2! = lis lis3)))
1896 (if (null? lists) lis
1897 (fold (lambda (lis1 lis2) (lset-union-2! = lis1 lis2))
1898 lis lists)))))))
1899
1900
1901 (define lset-intersection
1902 (case-lambda
1903 ((= lis1)
1904 (check-arg procedure? = lset-intersection)
1905 lis1)
1906 ((= lis1 lis2)
1907 (check-arg procedure? = lset-intersection)
1908 (cond
1909 ((or (null-list? lis1) (eq? lis1 lis2))
1910 lis1)
1911 ((null-list? lis2) lis2)
1912 (else (filter (lambda (x) (member x lis2 =)) lis1))))
1913 ((= lis1 lis2 lis3 . lists)
1914 (check-arg procedure? = lset-intersection)
1915 (cond
1916 ;; Short cut
1917 ((or (null-list? lis1) (null-list? lis2) (null-list? lis3)
1918 (any null-list? lists))
1919 '())
1920 ;; Throw out lis2 (and lis3) if it is lis1
1921 ((eq? lis2 lis1)
1922 (if (eq? lis3 lis1)
1923 (apply lset-intersection = lis1 lists)
1924 (apply lset-intersection = lis1 lis3 lists)))
1925 ;; Throw out lis3 if it is either lis1 or lis2
1926 ((or (eq? lis3 lis1) (eq? lis3 lis2))
1927 (apply lset-intersection = lis1 lis2 lists))
1928 ;; Real procedure
1929 (else
1930 (let* ((lists (remove (lambda (lis)
1931 (or (eq? lis lis1) (eq? lis lis2) (eq? lis lis3)))
1932 lists)))
1933 (filter (lambda (x)
1934 (and (member x lis2 =)
1935 (member x lis3 =)
1936 (every (lambda (lis) (member x lis =))
1937 lists)))
1938 lis1)))))))
1939
1940 (define lset-intersection!
1941 (case-lambda
1942 ((= lis1) (check-arg procedure? = lset-intersection!) lis1)
1943 ((= lis1 lis2)
1944 (check-arg procedure? = lset-intersection!)
1945 (cond
1946 ((or (null-list? lis2) (eq? lis1 lis2))
1947 lis1)
1948 ((null-list? lis1) lis2)
1949 (else (filter! (lambda (x) (member x lis2 =)) lis1))))
1950 ((= lis1 lis2 lis3 . lists)
1951 (check-arg procedure? = lset-intersection!)
1952 (cond
1953 ;; Short cut
1954 ((or (null-list? lis1) (null-list? lis2) (null-list? lis3)
1955 (any null-list? lists))
1956 '())
1957 ;; Throw out lis2 (and lis3) if it is lis1
1958 ((eq? lis2 lis1)
1959 (if (eq? lis3 lis1)
1960 (apply lset-intersection! = lis1 lists)
1961 (apply lset-intersection! = lis1 lis3 lists)))
1962 ;; Throw out lis3 if it is either lis1 or lis2
1963 ((or (eq? lis3 lis1) (eq? lis3 lis2))
1964 (apply lset-intersection! = lis1 lis2 lists))
1965 ;; Real procedure
1966 (else
1967 (let ((lists (remove (lambda (lis)
1968 (or (eq? lis lis1) (eq? lis lis2) (eq? lis lis3)))
1969 lists))) ; Remove duplicates
1970 (filter! (lambda (x)
1971 (and (member x lis2 =)
1972 (member x lis3 =)
1973 (every (lambda (lis) (member x lis =))
1974 lists)))
1975 lis1)))))))
1976
1977
1978 (define lset-difference
1979 (case-lambda
1980 ((= lis1) (check-arg procedure? = lset-difference) lis1)
1981 ((= lis1 lis2)
1982 (check-arg procedure? = lset-difference)
1983 (cond
1984 ((null-list? lis2) lis1)
1985 ((or (null-list? lis1) (eq? lis1 lis2))
1986 '())
1987 (else (filter (lambda (x) (not (member x lis2 =))) lis1))))
1988 ((= lis1 lis2 lis3 . lists)
1989 (check-arg procedure? = lset-difference)
1990 (cond
1991 ;; Short cut
1992 ((or (null-list? lis1) (eq? lis1 lis2) (eq? lis1 lis3)
1993 (memq lis1 lists))
1994 '())
1995 ;; Throw out lis2 (or lis3) if it is nil
1996 ((null? lis2)
1997 (if (null? lis3)
1998 (apply lset-difference lis1 lists)
1999 (apply lset-difference lis1 lis3 lists)))
2000 ;; Throw out lis3 if it is lis2 or nil
2001 ((or (null? lis3) (eq? lis3 lis2))
2002 (apply lset-difference lis1 lis2 lists))
2003 ;; Real procedure
2004 (else
2005 (let ((lists (remove (lambda (lis)
2006 (or (null? lis) (eq? lis lis2) (eq? lis lis3)))
2007 lists))) ; Remove nil, lis2 and lis3
2008 (filter (lambda (x)
2009 (and (not (member x lis2 =))
2010 (not (member x lis3 =))
2011 (every (lambda (lis) (not (member x lis =)))
2012 lists)))
2013 lis1)))))))
2014
2015 (define lset-difference!
2016 (case-lambda
2017 ((= lis1) (check-arg procedure? = lset-difference!) lis1)
2018 ((= lis1 lis2)
2019 (check-arg procedure? = lset-difference!)
2020 (cond
2021 ((null-list? lis2) lis1)
2022 ((or (null-list? lis1) (eq? lis1 lis2))
2023 '())
2024 (else (filter! (lambda (x) (not (member x lis2 =))) lis1))))
2025 ((= lis1 lis2 lis3 . lists)
2026 (check-arg procedure? = lset-difference!)
2027 (cond
2028 ;; Short cut
2029 ((or (null-list? lis1) (eq? lis1 lis2) (eq? lis1 lis3)
2030 (memq lis1 lists))
2031 '())
2032 ;; Throw out lis2 (or lis3) if it is nil
2033 ((null? lis2)
2034 (if (null? lis3)
2035 (apply lset-difference lis1 lists)
2036 (apply lset-difference lis1 lis3 lists)))
2037 ;; Throw out lis3 if it is lis2 or nil
2038 ((or (null? lis3) (eq? lis3 lis2))
2039 (apply lset-difference lis1 lis2 lists))
2040 ;; Real procedure
2041 (else
2042 (let ((lists (remove (lambda (lis)
2043 (or (null? lis) (eq? lis lis2) (eq? lis lis3)))
2044 lists))) ; Remove nil, lis2 and lis3
2045 (filter! (lambda (x)
2046 (and (not (member x lis2 =))
2047 (every (lambda (lis) (not (member x lis =)))
2048 lists)))
2049 lis1)))))))
2050
2051
2052 (define lset-xor
2053 (let ((lset-xor-2
2054 (lambda (= b a) ; Compute A xor B:
2055 ;; Note that this code relies on the constant-time
2056 ;; short-cuts provided by LSET-DIFF+INTERSECTION,
2057 ;; LSET-DIFFERENCE & APPEND to provide constant-time short
2058 ;; cuts for the cases A = (), B = (), and A eq? B. It takes
2059 ;; a careful case analysis to see it, but it's carefully
2060 ;; built in.
2061
2062 ;; Compute a-b and a^b, then compute b-(a^b) and
2063 ;; cons it onto the front of a-b.
2064 (receive (a-b a-int-b) (lset-diff+intersection = a b)
2065 (cond ((null? a-b) (lset-difference = b a))
2066 ((null? a-int-b) (append b a))
2067 (else (fold (lambda (xb ans)
2068 (if (member xb a-int-b =) ans (cons xb ans)))
2069 a-b
2070 b)))))))
2071 (case-lambda
2072 ((=) (check-arg procedure? = lset-xor) '())
2073 ((= a) (check-arg procedure? = lset-xor) a)
2074 ((= a b)
2075 (check-arg procedure? = lset-xor)
2076 (lset-xor-2 = b a))
2077 ((= a b c . lists)
2078 (check-arg procedure? = lset-xor)
2079 (let* ((lis (lset-xor-2 = b a))
2080 (lis (lset-xor-2 = c lis)))
2081 (if (null? lists) lis
2082 (fold (lambda (b a) (lset-xor-2 = b a))
2083 lis lists)))))))
2084
2085 (define lset-xor!
2086 (let ((lset-xor-2!
2087 (lambda (= b a) ; Compute A xor B:
2088 ;; Note that this code relies on the constant-time
2089 ;; short-cuts provided by LSET-DIFF+INTERSECTION,
2090 ;; LSET-DIFFERENCE & APPEND to provide constant-time short
2091 ;; cuts for the cases A = (), B = (), and A eq? B. It takes
2092 ;; a careful case analysis to see it, but it's carefully
2093 ;; built in.
2094
2095 ;; Compute a-b and a^b, then compute b-(a^b) and
2096 ;; cons it onto the front of a-b.
2097 (receive (a-b a-int-b) (lset-diff+intersection! = a b)
2098 (cond ((null? a-b) (lset-difference! = b a))
2099 ((null? a-int-b) (append! b a))
2100 (else (pair-fold (lambda (b-pair ans)
2101 (if (member (car b-pair) a-int-b =) ans
2102 (begin (set-cdr! b-pair ans) b-pair)))
2103 a-b
2104 b)))))))
2105 (case-lambda
2106 ((=) (check-arg procedure? = lset-xor!) '())
2107 ((= a) (check-arg procedure? = lset-xor!) a)
2108 ((= a b)
2109 (check-arg procedure? = lset-xor!)
2110 (lset-xor-2! = b a))
2111 ((= a b c . lists)
2112 (check-arg procedure? = lset-xor!)
2113 (let* ((lis (lset-xor-2! = b a))
2114 (lis (lset-xor-2! = c lis)))
2115 (if (null? lists) lis
2116 (fold (lambda (b a) (lset-xor-2! = b a))
2117 lis lists)))))))
2118
2119
2120 (define lset-diff+intersection
2121 (case-lambda
2122 ;; Fast path 1
2123 ((= lis1)
2124 (check-arg procedure? = lset-diff+intersection)
2125 (values lis1 '()))
2126 ;; Fast path 2
2127 ((= lis1 lis2)
2128 (check-arg procedure? = lset-diff+intersection)
2129 (cond
2130 ((or (null-list? lis1) (eq? lis1 lis2)) (values '() lis1))
2131 ((null-list? lis2) (values lis1 '()))
2132 (else (partition (lambda (elt)
2133 (not (member elt lis2 =)))
2134 lis1))))
2135 ;; N-ary case
2136 ((= lis1 lis2 lis3 . lists)
2137 (check-arg procedure? = lset-diff+intersection)
2138 (cond
2139 ((or (null-list? lis1) (eq? lis1 lis2) (eq? lis1 lis3)
2140 (memq lis1 lists))
2141 (values '() lis1))
2142 ((null-list? lis2)
2143 (if (null-list? lis3)
2144 (apply lset-diff+intersection = lis1 lists)
2145 (apply lset-diff+intersection = lis1 lis3 lists)))
2146 ((or (null-list? lis3) (eq? lis3 lis2))
2147 (apply lset-diff+intersection = lis1 lis2 lists))
2148 (else
2149 (let ((lists (remove (lambda (lis)
2150 (or (null? lis) (eq? lis lis2) (eq? lis lis3)))
2151 lists)))
2152 (partition (lambda (elt)
2153 (not (or (member elt lis2 =)
2154 (member elt lis3 =)
2155 (any (lambda (lis) (member elt lis =))
2156 lists))))
2157 lis1)))))))
2158
2159 (define lset-diff+intersection!
2160 (case-lambda
2161 ;; Fast path 1
2162 ((= lis1)
2163 (check-arg procedure? = lset-diff+intersection!)
2164 (values lis1 '()))
2165 ;; Fast path 2
2166 ((= lis1 lis2)
2167 (check-arg procedure? = lset-diff+intersection!)
2168 (cond
2169 ((or (null-list? lis1) (eq? lis1 lis2)) (values '() lis1))
2170 ((null-list? lis2) (values lis1 '()))
2171 (else (partition! (lambda (elt)
2172 (not (member elt lis2 =)))
2173 lis1))))
2174 ;; N-ary case
2175 ((= lis1 lis2 lis3 . lists)
2176 (check-arg procedure? = lset-diff+intersection!)
2177 (cond
2178 ((or (null-list? lis1) (eq? lis1 lis2) (eq? lis1 lis3)
2179 (memq lis1 lists))
2180 (values '() lis1))
2181 ((null-list? lis2)
2182 (if (null-list? lis3)
2183 (apply lset-diff+intersection! = lis1 lists)
2184 (apply lset-diff+intersection! = lis1 lis3 lists)))
2185 ((or (null-list? lis3) (eq? lis3 lis2))
2186 (apply lset-diff+intersection = lis1 lis2 lists))
2187 (else
2188 (let ((lists (remove (lambda (lis)
2189 (or (null? lis) (eq? lis lis2) (eq? lis lis3)))
2190 lists)))
2191 (partition! (lambda (elt)
2192 (not (or (member elt lis2 =)
2193 (member elt lis3 =)
2194 (any (lambda (lis) (member elt lis =))
2195 lists))))
2196 lis1)))))))