0.pre8.83:
[sbcl.git] / src / code / list.lisp
1 ;;;; functions to implement lists
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 ;;;; KLUDGE: comment from CMU CL, what does it mean?
15 ;;;;   NSUBLIS, things at the beginning broken.
16 ;;;; -- WHN 20000127
17
18 (declaim (maybe-inline
19           tree-equal nth %setnth nthcdr last make-list append
20           nconc member member-if member-if-not tailp adjoin union
21           nunion intersection nintersection set-difference nset-difference
22           set-exclusive-or nset-exclusive-or subsetp acons assoc
23           assoc-if assoc-if-not rassoc rassoc-if rassoc-if-not subst subst-if
24           subst-if-not nsubst nsubst-if nsubst-if-not sublis nsublis))
25
26 ;;; These functions perform basic list operations.
27 (defun car (list) #!+sb-doc "Return the 1st object in a list." (car list))
28 (defun cdr (list)
29   #!+sb-doc "Return all but the first object in a list."
30   (cdr list))
31 (defun cadr (list) #!+sb-doc "Return the 2nd object in a list." (cadr list))
32 (defun cdar (list) #!+sb-doc "Return the cdr of the 1st sublist." (cdar list))
33 (defun caar (list) #!+sb-doc "Return the car of the 1st sublist." (caar list))
34 (defun cddr (list)
35   #!+sb-doc "Return all but the 1st two objects of a list."
36   (cddr list))
37 (defun caddr (list)
38   #!+sb-doc "Return the 1st object in the cddr of a list."
39   (caddr list))
40 (defun caadr (list)
41   #!+sb-doc "Return the 1st object in the cadr of a list."
42   (caadr list))
43 (defun caaar (list)
44   #!+sb-doc "Return the 1st object in the caar of a list."
45   (caaar list))
46 (defun cdaar (list)
47   #!+sb-doc "Return the cdr of the caar of a list."
48   (cdaar list))
49 (defun cddar (list)
50   #!+sb-doc "Return the cdr of the cdar of a list."
51   (cddar list))
52 (defun cdddr (list)
53   #!+sb-doc "Return the cdr of the cddr of a list."
54   (cdddr list))
55 (defun cadar (list)
56   #!+sb-doc "Return the car of the cdar of a list."
57   (cadar list))
58 (defun cdadr (list)
59   #!+sb-doc "Return the cdr of the cadr of a list."
60   (cdadr list))
61 (defun caaaar (list)
62   #!+sb-doc "Return the car of the caaar of a list."
63   (caaaar list))
64 (defun caaadr (list)
65   #!+sb-doc "Return the car of the caadr of a list."
66   (caaadr list))
67 (defun caaddr (list)
68   #!+sb-doc "Return the car of the caddr of a list."
69   (caaddr list))
70 (defun cadddr (list)
71   #!+sb-doc "Return the car of the cdddr of a list."
72   (cadddr list))
73 (defun cddddr (list)
74   #!+sb-doc "Return the cdr of the cdddr of a list."
75   (cddddr list))
76 (defun cdaaar (list)
77   #!+sb-doc "Return the cdr of the caaar of a list."
78   (cdaaar list))
79 (defun cddaar (list)
80   #!+sb-doc "Return the cdr of the cdaar of a list."
81   (cddaar list))
82 (defun cdddar (list)
83   #!+sb-doc "Return the cdr of the cddar of a list."
84   (cdddar list))
85 (defun caadar (list)
86   #!+sb-doc "Return the car of the cadar of a list."
87   (caadar list))
88 (defun cadaar (list)
89   #!+sb-doc "Return the car of the cdaar of a list."
90   (cadaar list))
91 (defun cadadr (list)
92   #!+sb-doc "Return the car of the cdadr of a list."
93   (cadadr list))
94 (defun caddar (list)
95   #!+sb-doc "Return the car of the cddar of a list."
96   (caddar list))
97 (defun cdaadr (list)
98   #!+sb-doc "Return the cdr of the caadr of a list."
99   (cdaadr list))
100 (defun cdadar (list)
101   #!+sb-doc "Return the cdr of the cadar of a list."
102   (cdadar list))
103 (defun cdaddr (list)
104   #!+sb-doc "Return the cdr of the caddr of a list."
105   (cdaddr list))
106 (defun cddadr (list)
107   #!+sb-doc "Return the cdr of the cdadr of a list."
108   (cddadr list))
109 (defun cons (se1 se2)
110   #!+sb-doc "Return a list with SE1 as the CAR and SE2 as the CDR."
111   (cons se1 se2))
112 \f
113 (declaim (maybe-inline tree-equal-test tree-equal-test-not))
114
115 (defun tree-equal-test-not (x y test-not)
116   (declare (type function test-not))
117   (cond ((consp x)
118          (and (consp y)
119               (tree-equal-test-not (car x) (car y) test-not)
120               (tree-equal-test-not (cdr x) (cdr y) test-not)))
121         ((consp y) nil)
122         ((not (funcall test-not x y)) t)
123         (t ())))
124
125 (defun tree-equal-test (x y test)
126   (declare (type function test))
127   (cond ((consp x)
128          (and (consp y)
129               (tree-equal-test (car x) (car y) test)
130               (tree-equal-test (cdr x) (cdr y) test)))
131         ((consp y) nil)
132         ((funcall test x y) t)
133         (t ())))
134
135 (defun tree-equal (x y &key (test #'eql testp) (test-not nil notp))
136   #!+sb-doc
137   "Return T if X and Y are isomorphic trees with identical leaves."
138   (when (and testp notp)
139     (error ":TEST and :TEST-NOT were both supplied."))
140   (if test-not
141       (tree-equal-test-not x y (%coerce-callable-to-fun test-not))
142       (tree-equal-test x y (%coerce-callable-to-fun test))))
143
144 (defun endp (object)
145   #!+sb-doc
146   "This is the recommended way to test for the end of a proper list. It
147    returns true if OBJECT is NIL, false if OBJECT is a CONS, and an error
148    for any other type of OBJECT."
149   (endp object))
150
151 (defun list-length (list)
152   #!+sb-doc
153   "Return the length of the given List, or Nil if the List is circular."
154   (do ((n 0 (+ n 2))
155        (y list (cddr y))
156        (z list (cdr z)))
157       (())
158     (declare (type fixnum n)
159              (type list y z))
160     (when (endp y) (return n))
161     (when (endp (cdr y)) (return (+ n 1)))
162     (when (and (eq y z) (> n 0)) (return nil))))
163
164 (defun nth (n list)
165   #!+sb-doc
166   "Return the nth object in a list where the car is the zero-th element."
167   (car (nthcdr n list)))
168
169 (defun first (list)
170   #!+sb-doc
171   "Return the 1st object in a list or NIL if the list is empty."
172   (car list))
173 (defun second (list)
174   "Return the 2nd object in a list or NIL if there is no 2nd object."
175   (cadr list))
176 (defun third (list)
177   #!+sb-doc
178   "Return the 3rd object in a list or NIL if there is no 3rd object."
179   (caddr list))
180 (defun fourth (list)
181   #!+sb-doc
182   "Return the 4th object in a list or NIL if there is no 4th object."
183   (cadddr list))
184 (defun fifth (list)
185   #!+sb-doc
186   "Return the 5th object in a list or NIL if there is no 5th object."
187   (car (cddddr list)))
188 (defun sixth (list)
189   #!+sb-doc
190   "Return the 6th object in a list or NIL if there is no 6th object."
191   (cadr (cddddr list)))
192 (defun seventh (list)
193   #!+sb-doc
194   "Return the 7th object in a list or NIL if there is no 7th object."
195   (caddr (cddddr list)))
196 (defun eighth (list)
197   #!+sb-doc
198   "Return the 8th object in a list or NIL if there is no 8th object."
199   (cadddr (cddddr list)))
200 (defun ninth (list)
201   #!+sb-doc
202   "Return the 9th object in a list or NIL if there is no 9th object."
203   (car (cddddr (cddddr list))))
204 (defun tenth (list)
205   #!+sb-doc
206   "Return the 10th object in a list or NIL if there is no 10th object."
207   (cadr (cddddr (cddddr list))))
208 (defun rest (list)
209   #!+sb-doc
210   "Means the same as the cdr of a list."
211   (cdr list))
212
213 (defun nthcdr (n list)
214   (declare (type index n))
215   #!+sb-doc
216   "Performs the cdr function n times on a list."
217   (do ((i n (1- i))
218        (result list (cdr result)))
219       ((not (plusp i)) result)
220       (declare (type index i))))
221
222 (defun last (list &optional (n 1))
223   #!+sb-doc
224   "Return the last N conses (not the last element!) of a list."
225   (declare (type index n))
226   (do ((checked-list list (cdr checked-list))
227        (returned-list list)
228        (index 0 (1+ index)))
229       ((atom checked-list) returned-list)
230     (declare (type index index))
231     (if (>= index n)
232         (pop returned-list))))
233
234 (defun list (&rest args)
235   #!+sb-doc
236   "Return constructs and returns a list of its arguments."
237   args)
238
239 ;;; LIST* is done the same as LIST, except that the last cons is made
240 ;;; a dotted pair.
241
242 (defun list* (arg &rest others)
243   #!+sb-doc
244   "Return a list of the arguments with last cons a dotted pair"
245   (cond ((atom others) arg)
246         ((atom (cdr others)) (cons arg (car others)))
247         (t (do ((x others (cdr x)))
248                ((null (cddr x)) (rplacd x (cadr x))))
249            (cons arg others))))
250
251 (defun make-list (size &key initial-element)
252   #!+sb-doc
253   "Constructs a list with size elements each set to value"
254   (declare (type index size))
255   (do ((count size (1- count))
256        (result '() (cons initial-element result)))
257       ((zerop count) result)
258     (declare (type index count))))
259 \f
260 (defun append (&rest lists)
261   #!+sb-doc
262   "Construct a new list by concatenating the list arguments"
263   (labels ((fail (object)
264              (error 'type-error
265                     :datum object
266                     :expected-type 'list))
267            (append-into (last-cons current rest)
268              "Set (CDR LAST-CONS) to (APPLY #'APPEND CURRENT REST)."
269              (declare (cons last-cons rest))
270              (cond ((consp current)
271                     (append-into (setf (cdr last-cons) (list (car current)))
272                                 (cdr current)
273                                 rest))
274                    ((not (null current)) (fail current))
275                    ((null (cdr rest)) (setf (cdr last-cons) (car rest)))
276                    (t (append-into last-cons (car rest) (cdr rest)))))
277            (append1 (lists)
278              (let ((current (car lists))
279                    (rest (cdr lists)))
280                (cond ((null rest) current)
281                      ((consp current)
282                       (let ((result (truly-the cons (list (car current)))))
283                         (append-into result
284                                     (cdr current)
285                                     rest)
286                         result))
287                      ((null current) (append1 rest))
288                      (t (fail current))))))
289     (append1 lists)))
290 \f
291 ;;;; list copying functions
292
293 (defun copy-list (list)
294   #!+sb-doc
295   "Return a new list which is EQUAL to LIST."
296   ;; The list is copied correctly even if the list is not terminated
297   ;; by NIL. The new list is built by CDR'ing SPLICE which is always
298   ;; at the tail of the new list.
299   (if (atom list)
300       list
301       (let ((result (list (car list))))
302         (do ((x (cdr list) (cdr x))
303              (splice result
304                      (cdr (rplacd splice (cons (car x) '())))))
305             ((atom x)
306              (unless (null x)
307                (rplacd splice x))))
308         result)))
309
310 (defun copy-alist (alist)
311   #!+sb-doc
312   "Return a new association list which is EQUAL to ALIST."
313   (if (endp alist)
314       alist
315       (let ((result
316              (cons (if (atom (car alist))
317                        (car alist)
318                        (cons (caar alist) (cdar alist)))
319                    nil)))
320         (do ((x (cdr alist) (cdr x))
321              (splice result
322                      (cdr (rplacd splice
323                                   (cons
324                                    (if (atom (car x))
325                                        (car x)
326                                        (cons (caar x) (cdar x)))
327                                    nil)))))
328             ((endp x)))
329         result)))
330
331 (defun copy-tree (object)
332   #!+sb-doc
333   "Recursively copy trees of conses."
334   (if (consp object)
335       (cons (copy-tree (car object)) (copy-tree (cdr object)))
336       object))
337 \f
338 ;;;; more commonly-used list functions
339
340 (defun revappend (x y)
341   #!+sb-doc
342   "Return (append (reverse x) y)."
343   (do ((top x (cdr top))
344        (result y (cons (car top) result)))
345       ((endp top) result)))
346
347 ;;; NCONC finds the first non-null list, so it can make splice point
348 ;;; to a cons. After finding the first cons element, it holds it in a
349 ;;; result variable while running down successive elements tacking
350 ;;; them together. While tacking lists together, if we encounter a
351 ;;; null list, we set the previous list's last cdr to nil just in case
352 ;;; it wasn't already nil, and it could have been dotted while the
353 ;;; null list was the last argument to NCONC. The manipulation of
354 ;;; splice (that is starting it out on a first cons, setting LAST of
355 ;;; splice, and setting splice to ele) inherently handles (nconc x x),
356 ;;; and it avoids running down the last argument to NCONC which allows
357 ;;; the last argument to be circular.
358 (defun nconc (&rest lists)
359   #!+sb-doc
360   "Concatenates the lists given as arguments (by changing them)"
361   (flet ((fail (object)
362            (error 'type-error
363                   :datum object
364                   :expected-type 'list)))
365     (do ((top lists (cdr top)))
366         ((null top) nil)
367       (let ((top-of-top (car top)))
368         (typecase top-of-top
369           (cons
370            (let* ((result top-of-top)
371                   (splice result))
372              (do ((elements (cdr top) (cdr elements)))
373                  ((endp elements))
374                (let ((ele (car elements)))
375                  (typecase ele
376                    (cons (rplacd (last splice) ele)
377                          (setf splice ele))
378                    (null (rplacd (last splice) nil))
379                    (atom (if (cdr elements)
380                              (fail ele)
381                              (rplacd (last splice) ele)))
382                    (t (fail ele)))))
383              (return result)))
384           (null)
385           (atom
386            (if (cdr top)
387                (fail top-of-top)
388                (return top-of-top)))
389           (t (fail top-of-top)))))))
390
391 (defun nreconc (x y)
392   #!+sb-doc
393   "Return (NCONC (NREVERSE X) Y)."
394   (do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
395        (2nd x 1st)              ;2nd follows first down the list.
396        (3rd y 2nd))             ;3rd follows 2nd down the list.
397       ((atom 2nd) 3rd)
398     (rplacd 2nd 3rd)))
399 \f
400 (flet (;; Return the number of conses at the head of the
401        ;; possibly-improper list LIST. (Or if LIST is circular, you
402        ;; lose.)
403        (count-conses (list)
404          (do ((in-list list (cdr in-list))
405               (result 0 (1+ result)))
406              ((atom in-list)
407               result)
408            (declare (type index result)))))
409   (declare (ftype (function (t) index) count-conses))
410   (defun butlast (list &optional (n 1))
411     (let ((n-conses-in-list (count-conses list)))
412       (cond ((zerop n)
413              ;; (We can't use SUBSEQ in this case because LIST isn't
414              ;; necessarily a proper list, but SUBSEQ expects a
415              ;; proper sequence. COPY-LIST isn't so fussy.)
416              (copy-list list))
417             ((>= n n-conses-in-list)
418              nil)
419             (t
420              ;; (LIST isn't necessarily a proper list in this case
421              ;; either, and technically SUBSEQ wants a proper
422              ;; sequence, but no reasonable implementation of SUBSEQ
423              ;; will actually walk down to the end of the list to
424              ;; check, and since we're calling our own implementation
425              ;; we know it's reasonable, so it's OK.)
426              (subseq list 0 (- n-conses-in-list n))))))
427   (defun nbutlast (list &optional (n 1))
428     (if (zerop n)
429         list
430         (let ((n-conses-in-list (count-conses list)))
431           (unless (<= n-conses-in-list n)
432             (setf (cdr (nthcdr (- n-conses-in-list n 1) list))
433                   nil)
434             list)))))
435
436 (defun ldiff (list object)
437   "Return a new list, whose elements are those of LIST that appear before
438    OBJECT. If OBJECT is not a tail of LIST, a copy of LIST is returned.
439    LIST must be a proper list or a dotted list."
440   (do* ((list list (cdr list))
441         (result (list ()))
442         (splice result))
443        ((atom list)
444         (if (eql list object)
445             (cdr result)
446             (progn (rplacd splice list) (cdr result))))
447     (if (eql list object)
448         (return (cdr result))
449         (setq splice (cdr (rplacd splice (list (car list))))))))
450 \f
451 ;;;; functions to alter list structure
452
453 (defun rplaca (x y)
454   #!+sb-doc
455   "Change the CAR of X to Y and return the new X."
456   (rplaca x y))
457
458 (defun rplacd (x y)
459   #!+sb-doc
460   "Change the CDR of X to Y and return the new X."
461   (rplacd x y))
462
463 ;;; The following are for use by SETF.
464
465 (defun %rplaca (x val) (rplaca x val) val)
466
467 (defun %rplacd (x val) (rplacd x val) val)
468
469 ;;; Set the Nth element of LIST to NEWVAL.
470 (defun %setnth (n list newval)
471   (declare (type index n))
472   (do ((count n (1- count))
473        (list list (cdr list)))
474       ((endp list)
475        (error "~S is too large an index for SETF of NTH." n))
476     (declare (type fixnum count))
477     (when (<= count 0)
478       (rplaca list newval)
479       (return newval))))
480 \f
481 ;;;; :KEY arg optimization to save funcall of IDENTITY
482
483 ;;; APPLY-KEY saves us a function call sometimes.
484 ;;;    This isn't wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
485 ;;;    because it's used in seq.lisp and sort.lisp.
486 (defmacro apply-key (key element)
487   `(if ,key
488        (funcall ,key ,element)
489        ,element))
490 \f
491 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
492
493 ;;; Use these with the following &KEY args:
494 (defmacro with-set-keys (funcall)
495   `(if notp
496        ,(append funcall '(:key key :test-not test-not))
497        ,(append funcall '(:key key :test test))))
498
499 (defmacro satisfies-the-test (item elt)
500   (let ((key-tmp (gensym)))
501     `(let ((,key-tmp (apply-key key ,elt)))
502       (cond (testp (funcall test ,item ,key-tmp))
503             (notp (not (funcall test-not ,item ,key-tmp)))
504             (t (funcall test ,item ,key-tmp))))))
505 \f
506 ;;;; substitution of expressions
507
508 (defun subst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
509   #!+sb-doc
510   "Substitutes new for subtrees matching old."
511   (when (and testp notp)
512     (error ":TEST and :TEST-NOT were both supplied."))
513   (let ((key (and key (%coerce-callable-to-fun key)))
514         (test (if testp (%coerce-callable-to-fun test) test))
515         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
516     (declare (type function test test-not))
517     (labels ((s (subtree)
518                (cond ((satisfies-the-test old subtree) new)
519                      ((atom subtree) subtree)
520                      (t (let ((car (s (car subtree)))
521                               (cdr (s (cdr subtree))))
522                           (if (and (eq car (car subtree))
523                                    (eq cdr (cdr subtree)))
524                               subtree
525                               (cons car cdr)))))))
526       (s tree))))
527
528 (defun subst-if (new test tree &key key)
529   #!+sb-doc
530   "Substitutes new for subtrees for which test is true."
531   (let ((test (%coerce-callable-to-fun test))
532         (key (and key (%coerce-callable-to-fun key))))
533     (labels ((s (subtree)
534                (cond ((funcall test (apply-key key subtree)) new)
535                      ((atom subtree) subtree)
536                      (t (let ((car (s (car subtree)))
537                               (cdr (s (cdr subtree))))
538                           (if (and (eq car (car subtree))
539                                    (eq cdr (cdr subtree)))
540                               subtree
541                               (cons car cdr)))))))
542       (s tree))))
543
544 (defun subst-if-not (new test tree &key key)
545   #!+sb-doc
546   "Substitutes new for subtrees for which test is false."
547   (let ((test (%coerce-callable-to-fun test))
548         (key (and key (%coerce-callable-to-fun key))))
549     (labels ((s (subtree)
550                (cond ((not (funcall test (apply-key key subtree))) new)
551                      ((atom subtree) subtree)
552                      (t (let ((car (s (car subtree)))
553                               (cdr (s (cdr subtree))))
554                           (if (and (eq car (car subtree))
555                                    (eq cdr (cdr subtree)))
556                               subtree
557                               (cons car cdr)))))))
558       (s tree))))
559
560 (defun nsubst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
561   #!+sb-doc
562   "Substitute NEW for subtrees matching OLD."
563   (when (and testp notp)
564     (error ":TEST and :TEST-NOT were both supplied."))
565   (let ((key (and key (%coerce-callable-to-fun key)))
566         (test (if testp (%coerce-callable-to-fun test) test))
567         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
568     (declare (type function test test-not))
569     (labels ((s (subtree)
570                (cond ((satisfies-the-test old subtree) new)
571                      ((atom subtree) subtree)
572                      (t (do* ((last nil subtree)
573                               (subtree subtree (Cdr subtree)))
574                              ((atom subtree)
575                               (if (satisfies-the-test old subtree)
576                                   (setf (cdr last) new)))
577                           (if (satisfies-the-test old subtree)
578                               (return (setf (cdr last) new))
579                               (setf (car subtree) (s (car subtree)))))
580                         subtree))))
581       (s tree))))
582
583 (defun nsubst-if (new test tree &key key)
584   #!+sb-doc
585   "Substitute NEW for subtrees of TREE for which TEST is true."
586   (let ((test (%coerce-callable-to-fun test))
587         (key (and key (%coerce-callable-to-fun key))))
588     (labels ((s (subtree)
589                (cond ((funcall test (apply-key key subtree)) new)
590                      ((atom subtree) subtree)
591                      (t (do* ((last nil subtree)
592                               (subtree subtree (Cdr subtree)))
593                              ((atom subtree)
594                               (if (funcall test (apply-key key subtree))
595                                   (setf (cdr last) new)))
596                           (if (funcall test (apply-key key subtree))
597                               (return (setf (cdr last) new))
598                               (setf (car subtree) (s (car subtree)))))
599                         subtree))))
600       (s tree))))
601
602 (defun nsubst-if-not (new test tree &key key)
603   #!+sb-doc
604   "Substitute NEW for subtrees of TREE for which TEST is false."
605   (let ((test (%coerce-callable-to-fun test))
606         (key (and key (%coerce-callable-to-fun key))))
607     (labels ((s (subtree)
608                (cond ((not (funcall test (apply-key key subtree))) new)
609                      ((atom subtree) subtree)
610                      (t (do* ((last nil subtree)
611                               (subtree subtree (Cdr subtree)))
612                              ((atom subtree)
613                               (if (not (funcall test (apply-key key subtree)))
614                                   (setf (cdr last) new)))
615                           (if (not (funcall test (apply-key key subtree)))
616                               (return (setf (cdr last) new))
617                               (setf (car subtree) (s (car subtree)))))
618                         subtree))))
619       (s tree))))
620 \f
621 (defun sublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
622   #!+sb-doc
623   "Substitute from ALIST into TREE nondestructively."
624   (when (and testp notp)
625     (error ":TEST and :TEST-NOT were both supplied."))
626   (let ((key (and key (%coerce-callable-to-fun key)))
627         (test (if testp (%coerce-callable-to-fun test) test))
628         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
629     (declare (type function test test-not))
630     (declare (inline assoc))
631     (labels ((s (subtree)
632                (let* ((key-val (apply-key key subtree))
633                       (assoc (if notp
634                                  (assoc key-val alist :test-not test-not)
635                                  (assoc key-val alist :test test))))
636                  (cond (assoc (cdr assoc))
637                        ((atom subtree) subtree)
638                        (t (let ((car (s (car subtree)))
639                                 (cdr (s (cdr subtree))))
640                             (if (and (eq car (car subtreE))
641                                      (eq cdr (cdr subtree)))
642                                 subtree
643                                 (cons car cdr))))))))
644       (s tree))))
645
646 ;;; This is in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
647 ;;; because it can be referenced in inline expansions.
648 (defmacro nsublis-macro ()
649   (let ((key-tmp (gensym)))
650     `(let ((,key-tmp (apply-key key subtree)))
651       (if notp
652           (assoc ,key-tmp alist :test-not test-not)
653           (assoc ,key-tmp alist :test test)))))
654
655 (defun nsublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
656   #!+sb-doc
657   "Substitute from ALIST into TRUE destructively."
658   (when (and testp notp)
659     (error ":TEST and :TEST-NOT were both supplied."))
660   (let ((key (and key (%coerce-callable-to-fun key)))
661         (test (if testp (%coerce-callable-to-fun test) test))
662         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
663     (declare (inline assoc))
664     (let (temp)
665       (labels ((s (subtree)
666                  (cond ((Setq temp (nsublis-macro))
667                         (cdr temp))
668                        ((atom subtree) subtree)
669                        (t (do* ((last nil subtree)
670                                 (subtree subtree (Cdr subtree)))
671                                ((atom subtree)
672                                 (if (setq temp (nsublis-macro))
673                                     (setf (cdr last) (cdr temp))))
674                             (if (setq temp (nsublis-macro))
675                                 (return (setf (Cdr last) (Cdr temp)))
676                                 (setf (car subtree) (s (car subtree)))))
677                           subtree))))
678         (s tree)))))
679 \f
680 ;;;; functions for using lists as sets
681
682 (defun member (item list &key key (test #'eql testp) (test-not #'eql notp))
683   #!+sb-doc
684   "Return the tail of LIST beginning with first element satisfying EQLity,
685    :TEST, or :TEST-NOT with the given ITEM."
686   (when (and testp notp)
687     (error ":TEST and :TEST-NOT were both supplied."))
688   (let ((key (and key (%coerce-callable-to-fun key)))
689         (test (if testp (%coerce-callable-to-fun test) test))
690         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
691     (declare (type function test test-not))
692     (do ((list list (cdr list)))
693         ((null list) nil)
694       (let ((car (car list)))
695         (if (satisfies-the-test item car)
696             (return list))))))
697
698 (defun member-if (test list &key key)
699   #!+sb-doc
700   "Return tail of LIST beginning with first element satisfying TEST."
701   (let ((test (%coerce-callable-to-fun test))
702         (key (and key (%coerce-callable-to-fun key))))
703     (do ((list list (cdr list)))
704         ((endp list) nil)
705       (if (funcall test (apply-key key (car list)))
706           (return list)))))
707
708 (defun member-if-not (test list &key key)
709   #!+sb-doc
710   "Return tail of LIST beginning with first element not satisfying TEST."
711   (let ((test (%coerce-callable-to-fun test))
712         (key (and key (%coerce-callable-to-fun key))))
713     (do ((list list (cdr list)))
714         ((endp list) ())
715       (if (not (funcall test (apply-key key (car list))))
716           (return list)))))
717
718 (defun tailp (object list)
719   #!+sb-doc
720   "Return true if OBJECT is the same as some tail of LIST, otherwise
721    returns false. LIST must be a proper list or a dotted list."
722   (do ((list list (cdr list)))
723       ((atom list) (eql list object))
724     (if (eql object list)
725         (return t))))
726
727 (defun adjoin (item list &key key (test #'eql testp) (test-not nil notp))
728   #!+sb-doc
729   "Add ITEM to LIST unless it is already a member"
730   (when (and testp notp)
731     (error ":TEST and :TEST-NOT were both supplied."))
732   (let ((key (and key (%coerce-callable-to-fun key))))
733     (declare (inline member))
734     (if (let ((key-val (apply-key key item)))
735           (if notp
736               (member key-val list :test-not test-not :key key)
737               (member key-val list :test test :key key)))
738         list
739         (cons item list))))
740
741 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
742   #!+sb-doc
743   "Return the union of LIST1 and LIST2."
744   (declare (inline member))
745   (when (and testp notp)
746     (error ":TEST and :TEST-NOT were both supplied."))
747   ;; We assumes LIST2 is the result, adding to it from LIST1 as
748   ;; necessary. LIST2 must initialize the result value, so the call to
749   ;; MEMBER will apply the test to the elements from LIST1 and LIST2
750   ;; in the correct order.
751   (let ((key (and key (%coerce-callable-to-fun key))))
752     (let ((res list2))
753       (dolist (elt list1)
754         (unless (with-set-keys (member (apply-key key elt) list2))
755           (push elt res)))
756       res)))
757
758 ;;; Destination and source are SETF-able and many-evaluable. Set the
759 ;;; SOURCE to the CDR, and "cons" the 1st elt of source to DESTINATION.
760 ;;;
761 ;;; FIXME: needs a more mnemonic name
762 (defmacro steve-splice (source destination)
763   `(let ((temp ,source))
764      (setf ,source (cdr ,source)
765            (cdr temp) ,destination
766            ,destination temp)))
767
768 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
769   #!+sb-doc
770   "Destructively return the union of LIST1 and LIST2."
771   (declare (inline member))
772   (when (and testp notp)
773     (error ":TEST and :TEST-NOT were both supplied."))
774   (let ((key (and key (%coerce-callable-to-fun key))))
775     (let ((res list2)
776           (list1 list1))
777       (do ()
778           ((endp list1))
779         (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
780             (steve-splice list1 res)
781             (setf list1 (cdr list1))))
782       res)))
783
784 (defun intersection (list1 list2
785                      &key key (test #'eql testp) (test-not nil notp))
786   #!+sb-doc
787   "Return the intersection of LIST1 and LIST2."
788   (declare (inline member))
789   (when (and testp notp)
790     (error ":TEST and :TEST-NOT were both supplied."))
791   (let ((key (and key (%coerce-callable-to-fun key))))
792     (let ((res nil))
793       (dolist (elt list1)
794         (if (with-set-keys (member (apply-key key elt) list2))
795             (push elt res)))
796       res)))
797
798 (defun nintersection (list1 list2
799                       &key key (test #'eql testp) (test-not nil notp))
800   #!+sb-doc
801   "Destructively return the intersection of LIST1 and LIST2."
802   (declare (inline member))
803   (when (and testp notp)
804     (error ":TEST and :TEST-NOT were both supplied."))
805   (let ((key (and key (%coerce-callable-to-fun key))))
806     (let ((res nil)
807           (list1 list1))
808       (do () ((endp list1))
809         (if (with-set-keys (member (apply-key key (car list1)) list2))
810             (steve-splice list1 res)
811             (setq list1 (Cdr list1))))
812       res)))
813
814 (defun set-difference (list1 list2
815                        &key key (test #'eql testp) (test-not nil notp))
816   #!+sb-doc
817   "Return the elements of LIST1 which are not in LIST2."
818   (declare (inline member))
819   (when (and testp notp)
820     (error ":TEST and :TEST-NOT were both supplied."))
821   (let ((key (and key (%coerce-callable-to-fun key))))
822     (if (null list2)
823         list1
824         (let ((res nil))
825           (dolist (elt list1)
826             (if (not (with-set-keys (member (apply-key key elt) list2)))
827                 (push elt res)))
828           res))))
829
830 (defun nset-difference (list1 list2
831                         &key key (test #'eql testp) (test-not nil notp))
832   #!+sb-doc
833   "Destructively return the elements of LIST1 which are not in LIST2."
834   (declare (inline member))
835   (when (and testp notp)
836     (error ":TEST and :TEST-NOT were both supplied."))
837   (let ((key (and key (%coerce-callable-to-fun key))))
838     (let ((res nil)
839           (list1 list1))
840       (do () ((endp list1))
841         (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
842             (steve-splice list1 res)
843             (setq list1 (cdr list1))))
844       res)))
845
846 (defun set-exclusive-or (list1 list2
847                          &key key (test #'eql testp) (test-not #'eql notp))
848   #!+sb-doc
849   "Return new list of elements appearing exactly once in LIST1 and LIST2."
850   (declare (inline member))
851   (when (and testp notp)
852     (error ":TEST and :TEST-NOT were both supplied."))
853   (let ((result nil)
854         (key (and key (%coerce-callable-to-fun key)))
855         (test (if testp (%coerce-callable-to-fun test) test))
856         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
857     (declare (type function test test-not))
858     (dolist (elt list1)
859       (unless (with-set-keys (member (apply-key key elt) list2))
860         (setq result (cons elt result))))
861     (let ((test (if testp
862                     (lambda (x y) (funcall test y x))
863                     test))
864           (test-not (if notp
865                         (lambda (x y) (funcall test-not y x))
866                         test-not)))
867       (dolist (elt list2)
868         (unless (with-set-keys (member (apply-key key elt) list1))
869           (setq result (cons elt result)))))
870     result))
871
872 (defun nset-exclusive-or (list1 list2
873                           &key key (test #'eql testp) (test-not #'eql notp))
874   #!+sb-doc
875   "Destructively return a list with elements which appear but once in LIST1
876    and LIST2."
877   (when (and testp notp)
878     (error ":TEST and :TEST-NOT were both supplied."))
879   (let ((key (and key (%coerce-callable-to-fun key)))
880         (test (if testp (%coerce-callable-to-fun test) test))
881         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
882     (declare (type function test test-not))
883     ;; The outer loop examines LIST1 while the inner loop examines
884     ;; LIST2. If an element is found in LIST2 "equal" to the element
885     ;; in LIST1, both are spliced out. When the end of LIST1 is
886     ;; reached, what is left of LIST2 is tacked onto what is left of
887     ;; LIST1. The splicing operation ensures that the correct
888     ;; operation is performed depending on whether splice is at the
889     ;; top of the list or not.
890     (do ((list1 list1)
891          (list2 list2)
892          (x list1 (cdr x))
893          (splicex ())
894          (deleted-y ())
895          ;; elements of LIST2, which are "equal" to some processed
896          ;; earlier elements of LIST1
897          )
898         ((endp x)
899          (if (null splicex)
900              (setq list1 list2)
901              (rplacd splicex list2))
902          list1)
903       (let ((key-val-x (apply-key key (car x)))
904             (found-duplicate nil))
905
906         ;; Move all elements from LIST2, which are "equal" to (CAR X),
907         ;; to DELETED-Y.
908         (do* ((y list2 next-y)
909               (next-y (cdr y) (cdr y))
910               (splicey ()))
911              ((endp y))
912           (cond ((let ((key-val-y (apply-key key (car y))))
913                    (if notp
914                        (not (funcall test-not key-val-x key-val-y))
915                        (funcall test key-val-x key-val-y)))
916                  (if (null splicey)
917                      (setq list2 (cdr y))
918                      (rplacd splicey (cdr y)))
919                  (setq deleted-y (rplacd y deleted-y))
920                  (setq found-duplicate t))
921                 (t (setq splicey y))))
922
923         (unless found-duplicate
924           (setq found-duplicate (with-set-keys (member key-val-x deleted-y))))
925
926         (if found-duplicate
927             (if (null splicex)
928                 (setq list1 (cdr x))
929                 (rplacd splicex (cdr x)))
930             (setq splicex x))))))
931
932 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
933   #!+sb-doc
934   "Return T if every element in LIST1 is also in LIST2."
935   (declare (inline member))
936   (when (and testp notp)
937     (error ":TEST and :TEST-NOT were both supplied."))
938   (let ((key (and key (%coerce-callable-to-fun key))))
939     (dolist (elt list1)
940       (unless (with-set-keys (member (apply-key key elt) list2))
941         (return-from subsetp nil)))
942     t))
943 \f
944 ;;;; functions that operate on association lists
945
946 (defun acons (key datum alist)
947   #!+sb-doc
948   "Construct a new alist by adding the pair (KEY . DATUM) to ALIST."
949   (cons (cons key datum) alist))
950
951 (defun pairlis (keys data &optional (alist '()))
952   #!+sb-doc
953   "Construct an association list from KEYS and DATA (adding to ALIST)."
954   (do ((x keys (cdr x))
955        (y data (cdr y)))
956       ((and (endp x) (endp y)) alist)
957     (if (or (endp x) (endp y))
958         (error "The lists of keys and data are of unequal length."))
959     (setq alist (acons (car x) (car y) alist))))
960
961 ;;; This is defined in the run-time environment, not just the compile-time
962 ;;; environment (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL)) because it
963 ;;; can appear in inline expansions.
964 (defmacro assoc-guts (test-expr)
965   `(do ((alist alist (cdr alist)))
966        ((endp alist))
967     (when (and (car alist) ,test-expr)
968       (return (car alist)))))
969
970 (defun assoc (item alist &key key (test nil testp) (test-not nil notp))
971   #!+sb-doc
972   "Return the cons in ALIST whose car is equal (by a given test or EQL) to
973    the ITEM."
974   (when (and testp notp)
975     (error ":TEST and :TEST-NOT were both supplied."))
976   (let ((key (and key (%coerce-callable-to-fun key)))
977         (test (and testp (%coerce-callable-to-fun test)))
978         (test-not (and notp (%coerce-callable-to-fun test-not))))
979     (cond (test
980            (if key
981                (assoc-guts (funcall test item (funcall key (caar alist))))
982                (assoc-guts (funcall test item (caar alist)))))
983           (test-not
984            (if key
985                (assoc-guts (not (funcall test-not item
986                                          (funcall key (caar alist)))))
987                (assoc-guts (not (funcall test-not item (caar alist))))))
988           (t
989            (if key
990                (assoc-guts (eql item (funcall key (caar alist))))
991                (assoc-guts (eql item (caar alist))))))))
992
993 (defun assoc-if (predicate alist &key key)
994   #!+sb-doc
995   "Return the first cons in ALIST whose CAR satisfies PREDICATE. If
996    KEY is supplied, apply it to the CAR of each cons before testing."
997   (let ((predicate (%coerce-callable-to-fun predicate))
998         (key (and key (%coerce-callable-to-fun key))))
999     (if key
1000         (assoc-guts (funcall predicate (funcall key (caar alist))))
1001         (assoc-guts (funcall predicate (caar alist))))))
1002
1003 (defun assoc-if-not (predicate alist &key key)
1004   #!+sb-doc
1005   "Return the first cons in ALIST whose CAR does not satisfy PREDICATE.
1006   If KEY is supplied, apply it to the CAR of each cons before testing."
1007   (let ((predicate (%coerce-callable-to-fun predicate))
1008         (key (and key (%coerce-callable-to-fun key))))
1009     (if key
1010         (assoc-guts (not (funcall predicate (funcall key (caar alist)))))
1011         (assoc-guts (not (funcall predicate (caar alist)))))))
1012
1013 (defun rassoc (item alist &key key (test nil testp) (test-not nil notp))
1014   (declare (list alist))
1015   #!+sb-doc
1016   "Return the cons in ALIST whose CDR is equal (by a given test or EQL) to
1017    the ITEM."
1018   (when (and testp notp)
1019     (error ":TEST and :TEST-NOT were both supplied."))
1020   (let ((key (and key (%coerce-callable-to-fun key)))
1021         (test (and testp (%coerce-callable-to-fun test)))
1022         (test-not (and notp (%coerce-callable-to-fun test-not))))
1023     (cond (test
1024            (if key
1025                (assoc-guts (funcall test item (funcall key (cdar alist))))
1026                (assoc-guts (funcall test item (cdar alist)))))
1027           (test-not
1028            (if key
1029                (assoc-guts (not (funcall test-not item
1030                                          (funcall key (cdar alist)))))
1031                (assoc-guts (not (funcall test-not item (cdar alist))))))
1032           (t
1033            (if key
1034                (assoc-guts (eql item (funcall key (cdar alist))))
1035                (assoc-guts (eql item (cdar alist))))))))
1036
1037 (defun rassoc-if (predicate alist &key key)
1038   #!+sb-doc
1039   "Return the first cons in ALIST whose CDR satisfies PREDICATE. If KEY
1040   is supplied, apply it to the CDR of each cons before testing."
1041   (let ((predicate (%coerce-callable-to-fun predicate))
1042         (key (and key (%coerce-callable-to-fun key))))
1043     (if key
1044         (assoc-guts (funcall predicate (funcall key (cdar alist))))
1045         (assoc-guts (funcall predicate (cdar alist))))))
1046
1047 (defun rassoc-if-not (predicate alist &key key)
1048   #!+sb-doc
1049   "Return the first cons in ALIST whose CDR does not satisfy PREDICATE.
1050   If KEY is supplied, apply it to the CDR of each cons before testing."
1051   (let ((predicate (%coerce-callable-to-fun predicate))
1052         (key (and key (%coerce-callable-to-fun key))))
1053     (if key
1054         (assoc-guts (not (funcall predicate (funcall key (cdar alist)))))
1055         (assoc-guts (not (funcall predicate (cdar alist)))))))
1056 \f
1057 ;;;; mapping functions
1058
1059 ;;; a helper function for implementation of MAPC, MAPCAR, MAPCAN,
1060 ;;; MAPL, MAPLIST, and MAPCON
1061 ;;;
1062 ;;; Map the designated function over the arglists in the appropriate
1063 ;;; way. It is done when any of the arglists runs out. Until then, it
1064 ;;; CDRs down the arglists calling the function and accumulating
1065 ;;; results as desired.
1066 (defun map1 (fun-designator original-arglists accumulate take-car)
1067   (let ((fun (%coerce-callable-to-fun fun-designator)))
1068     (let* ((arglists (copy-list original-arglists))
1069            (ret-list (list nil))
1070            (temp ret-list))
1071       (do ((res nil)
1072            (args '() '()))
1073           ((dolist (x arglists nil) (if (null x) (return t)))
1074            (if accumulate
1075                (cdr ret-list)
1076                (car original-arglists)))
1077         (do ((l arglists (cdr l)))
1078             ((null l))
1079           (push (if take-car (caar l) (car l)) args)
1080           (setf (car l) (cdar l)))
1081         (setq res (apply fun (nreverse args)))
1082         (case accumulate
1083           (:nconc (setq temp (last (nconc temp res))))
1084           (:list (rplacd temp (list res))
1085                  (setq temp (cdr temp))))))))
1086
1087 (defun mapc (function list &rest more-lists)
1088   #!+sb-doc
1089   "Apply FUNCTION to successive elements of lists. Return the second argument."
1090   (map1 function (cons list more-lists) nil t))
1091
1092 (defun mapcar (function list &rest more-lists)
1093   #!+sb-doc
1094   "Apply FUNCTION to successive elements of LIST. Return list of FUNCTION
1095    return values."
1096   (map1 function (cons list more-lists) :list t))
1097
1098 (defun mapcan (function list &rest more-lists)
1099   #!+sb-doc
1100   "Apply FUNCTION to successive elements of LIST. Return NCONC of FUNCTION
1101    results."
1102   (map1 function (cons list more-lists) :nconc t))
1103
1104 (defun mapl (function list &rest more-lists)
1105   #!+sb-doc
1106   "Apply FUNCTION to successive CDRs of list. Return NIL."
1107   (map1 function (cons list more-lists) nil nil))
1108
1109 (defun maplist (function list &rest more-lists)
1110   #!+sb-doc
1111   "Apply FUNCTION to successive CDRs of list. Return list of results."
1112   (map1 function (cons list more-lists) :list nil))
1113
1114 (defun mapcon (function list &rest more-lists)
1115   #!+sb-doc
1116   "Apply FUNCTION to successive CDRs of lists. Return NCONC of results."
1117   (map1 function (cons list more-lists) :nconc nil))