Debian Codegraph @

scheme/tests/SRFI-1.ss

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