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