0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[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 list-length nth %setnth nthcdr last make-list append
20           copy-list copy-alist copy-tree revappend nconc nreconc butlast
21           nbutlast ldiff member member-if member-if-not tailp adjoin union
22           nunion intersection nintersection set-difference nset-difference
23           set-exclusive-or nset-exclusive-or subsetp acons pairlis assoc
24           assoc-if assoc-if-not rassoc rassoc-if rassoc-if-not subst subst-if
25           subst-if-not nsubst nsubst-if nsubst-if-not sublis nsublis))
26
27 ;;; These functions perform basic list operations:
28 (defun car (list) #!+sb-doc "Returns the 1st object in a list." (car list))
29 (defun cdr (list)
30   #!+sb-doc "Returns all but the first object in a list."
31   (cdr list))
32 (defun cadr (list) #!+sb-doc "Returns the 2nd object in a list." (cadr list))
33 (defun cdar (list) #!+sb-doc "Returns the cdr of the 1st sublist." (cdar list))
34 (defun caar (list) #!+sb-doc "Returns the car of the 1st sublist." (caar list))
35 (defun cddr (list)
36   #!+sb-doc "Returns all but the 1st two objects of a list."
37   (cddr list))
38 (defun caddr (list)
39   #!+sb-doc "Returns the 1st object in the cddr of a list."
40   (caddr list))
41 (defun caadr (list)
42   #!+sb-doc "Returns the 1st object in the cadr of a list."
43   (caadr list))
44 (defun caaar (list)
45   #!+sb-doc "Returns the 1st object in the caar of a list."
46   (caaar list))
47 (defun cdaar (list)
48   #!+sb-doc "Returns the cdr of the caar of a list."
49   (cdaar list))
50 (defun cddar (list)
51   #!+sb-doc "Returns the cdr of the cdar of a list."
52   (cddar list))
53 (defun cdddr (list)
54   #!+sb-doc "Returns the cdr of the cddr of a list."
55   (cdddr list))
56 (defun cadar (list)
57   #!+sb-doc "Returns the car of the cdar of a list."
58   (cadar list))
59 (defun cdadr (list)
60   #!+sb-doc "Returns the cdr of the cadr of a list."
61   (cdadr list))
62 (defun caaaar (list)
63   #!+sb-doc "Returns the car of the caaar of a list."
64   (caaaar list))
65 (defun caaadr (list)
66   #!+sb-doc "Returns the car of the caadr of a list."
67   (caaadr list))
68 (defun caaddr (list)
69   #!+sb-doc "Returns the car of the caddr of a list."
70   (caaddr list))
71 (defun cadddr (list)
72   #!+sb-doc "Returns the car of the cdddr of a list."
73   (cadddr list))
74 (defun cddddr (list)
75   #!+sb-doc "Returns the cdr of the cdddr of a list."
76   (cddddr list))
77 (defun cdaaar (list)
78   #!+sb-doc "Returns the cdr of the caaar of a list."
79   (cdaaar list))
80 (defun cddaar (list)
81   #!+sb-doc "Returns the cdr of the cdaar of a list."
82   (cddaar list))
83 (defun cdddar (list)
84   #!+sb-doc "Returns the cdr of the cddar of a list."
85   (cdddar list))
86 (defun caadar (list)
87   #!+sb-doc "Returns the car of the cadar of a list."
88   (caadar list))
89 (defun cadaar (list)
90   #!+sb-doc "Returns the car of the cdaar of a list."
91   (cadaar list))
92 (defun cadadr (list)
93   #!+sb-doc "Returns the car of the cdadr of a list."
94   (cadadr list))
95 (defun caddar (list)
96   #!+sb-doc "Returns the car of the cddar of a list."
97   (caddar list))
98 (defun cdaadr (list)
99   #!+sb-doc "Returns the cdr of the caadr of a list."
100   (cdaadr list))
101 (defun cdadar (list)
102   #!+sb-doc "Returns the cdr of the cadar of a list."
103   (cdadar list))
104 (defun cdaddr (list)
105   #!+sb-doc "Returns the cdr of the caddr of a list."
106   (cdaddr list))
107 (defun cddadr (list)
108   #!+sb-doc "Returns the cdr of the cdadr of a list."
109   (cddadr list))
110 (defun cons (se1 se2)
111   #!+sb-doc "Returns a list with se1 as the car and se2 as the cdr."
112   (cons se1 se2))
113 \f
114 (declaim (maybe-inline tree-equal-test tree-equal-test-not))
115
116 (defun tree-equal-test-not (x y 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   (cond ((consp x)
127          (and (consp y)
128               (tree-equal-test (car x) (car y) test)
129               (tree-equal-test (cdr x) (cdr y) test)))
130         ((consp y) nil)
131         ((funcall test x y) t)
132         (t ())))
133
134 (defun tree-equal (x y &key (test #'eql) test-not)
135   #!+sb-doc
136   "Returns T if X and Y are isomorphic trees with identical leaves."
137   (if test-not
138       (tree-equal-test-not x y test-not)
139       (tree-equal-test x y test)))
140
141 (defun endp (object)
142   #!+sb-doc
143   "The recommended way to test for the end of a list. True if Object is nil,
144    false if Object is a cons, and an error for any other types of arguments."
145   (endp object))
146
147 (defun list-length (list)
148   #!+sb-doc
149   "Returns 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   "Returns 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   "Returns the 1st object in a list or NIL if the list is empty."
167   (car list))
168 (defun second (list)
169   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   (do ((top lists (cdr top)))    ;;Cdr to first non-null list.
263       ((atom top) '())
264     (cond ((null (car top)))                            ; Nil -> Keep looping
265           ((not (consp (car top)))                      ; Non cons
266            (if (cdr top)
267                (error "~S is not a list." (car top))
268                (return (car top))))
269           (t                                            ; Start appending
270            (return
271              (if (atom (cdr top))
272                  (car top)    ;;Special case.
273                  (let* ((result (cons (caar top) '()))
274                         (splice result))
275                    (do ((x (cdar top) (cdr x)))  ;;Copy first list
276                        ((atom x))
277                      (setq splice
278                            (cdr (rplacd splice (cons (car x) ()) ))) )
279                    (do ((y (cdr top) (cdr y)))   ;;Copy rest of lists.
280                        ((atom (cdr y))
281                         (setq splice (rplacd splice (car y)))
282                         result)
283                      (if (listp (car y))
284                          (do ((x (car y) (cdr x)))   ;;Inner copy loop.
285                              ((atom x))
286                            (setq
287                             splice
288                             (cdr (rplacd splice (cons (car x) ())))))
289                          (error "~S is not a list." (car y)))))))))))
290 \f
291 ;;; list copying functions
292
293 (defun copy-list (list)
294   #!+sb-doc
295   "Returns 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   "Returns a new association list which is EQUAL to ALIST."
313   (if (atom 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             ;; Non-null terminated alist done here.
329             ((atom x)
330              (unless (null x)
331                (rplacd splice x))))
332         result)))
333
334 (defun copy-tree (object)
335   #!+sb-doc
336   "Recursively copy trees of conses."
337   (if (consp object)
338       (cons (copy-tree (car object)) (copy-tree (cdr object)))
339       object))
340 \f
341 ;;; more commonly-used list functions
342
343 (defun revappend (x y)
344   #!+sb-doc
345   "Returns (append (reverse x) y)"
346   (do ((top x (cdr top))
347        (result y (cons (car top) result)))
348       ((endp top) result)))
349
350 ;;; NCONC finds the first non-null list, so it can make splice point
351 ;;; to a cons. After finding the first cons element, it holds it in a
352 ;;; result variable while running down successive elements tacking
353 ;;; them together. While tacking lists together, if we encounter a
354 ;;; null list, we set the previous list's last cdr to nil just in case
355 ;;; it wasn't already nil, and it could have been dotted while the
356 ;;; null list was the last argument to NCONC. The manipulation of
357 ;;; splice (that is starting it out on a first cons, setting LAST of
358 ;;; splice, and setting splice to ele) inherently handles (nconc x x),
359 ;;; and it avoids running down the last argument to NCONC which allows
360 ;;; the last argument to be circular.
361 (defun nconc (&rest lists)
362   #!+sb-doc
363   "Concatenates the lists given as arguments (by changing them)"
364   (do ((top lists (cdr top)))
365       ((null top) nil)
366     (let ((top-of-top (car top)))
367       (typecase top-of-top
368         (cons
369          (let* ((result top-of-top)
370                 (splice result))
371            (do ((elements (cdr top) (cdr elements)))
372                ((endp elements))
373              (let ((ele (car elements)))
374                (typecase ele
375                  (cons (rplacd (last splice) ele)
376                        (setf splice ele))
377                  (null (rplacd (last splice) nil))
378                  (atom (if (cdr elements)
379                            (error "Argument is not a list -- ~S." ele)
380                            (rplacd (last splice) ele)))
381                  (t (error "Argument is not a list -- ~S." ele)))))
382            (return result)))
383         (null)
384         (atom
385          (if (cdr top)
386              (error "Argument is not a list -- ~S." top-of-top)
387              (return top-of-top)))
388         (t (error "Argument is not a list -- ~S." top-of-top))))))
389
390 (defun nreconc (x y)
391   #!+sb-doc
392   "Returns (nconc (nreverse x) y)"
393   (do ((1st (cdr x) (if (atom 1st) 1st (cdr 1st)))
394        (2nd x 1st)              ;2nd follows first down the list.
395        (3rd y 2nd))             ;3rd follows 2nd down the list.
396       ((atom 2nd) 3rd)
397     (rplacd 2nd 3rd)))
398 \f
399 (flet (;; Return the number of conses at the head of the
400        ;; possibly-improper list LIST. (Or if LIST is circular, you
401        ;; lose.)
402        (count-conses (list)
403          (do ((in-list list (cdr in-list))
404               (result 0 (1+ result)))
405              ((atom in-list)
406               result)
407            (declare (type index result)))))
408   (declare (ftype (function (t) index) count-conses))
409   (defun butlast (list &optional (n 1))
410     (let* ((n-conses-in-list (count-conses list))
411            (n-remaining-to-copy (- n-conses-in-list n)))
412       (declare (type fixnum n-remaining-to-copy))
413       (when (plusp n-remaining-to-copy)
414         (do* ((result (list (first list)))
415               (rest (rest list) (rest rest))
416               (splice result))
417             ((zerop (decf n-remaining-to-copy))
418              result)
419           (setf splice
420                 (setf (cdr splice)
421                       (list (first rest))))))))
422   (defun nbutlast (list &optional (n 1))
423     (let ((n-conses-in-list (count-conses list)))
424       (unless (< n-conses-in-list n)
425         (setf (cdr (nthcdr (- n-conses-in-list n 1) list))
426               nil)
427         list))))
428
429 (defun ldiff (list object)
430   "Returns a new list, whose elements are those of List that appear before
431    Object. If Object is not a tail of List, a copy of List is returned.
432    List must be a proper list or a dotted list."
433   (do* ((list list (cdr list))
434         (result (list ()))
435         (splice result))
436        ((atom list)
437         (if (eql list object)
438             (cdr result)
439             (progn (rplacd splice list) (cdr result))))
440     (if (eql list object)
441         (return (cdr result))
442         (setq splice (cdr (rplacd splice (list (car list))))))))
443 \f
444 ;;;; functions to alter list structure
445
446 (defun rplaca (x y)
447   #!+sb-doc
448   "Changes the car of x to y and returns the new x."
449   (rplaca x y))
450
451 (defun rplacd (x y)
452   #!+sb-doc
453   "Changes the cdr of x to y and returns the new x."
454   (rplacd x y))
455
456 ;;; The following are for use by SETF.
457
458 (defun %rplaca (x val) (rplaca x val) val)
459
460 (defun %rplacd (x val) (rplacd x val) val)
461
462 (defun %setnth (n list newval)
463   (declare (type index n))
464   #!+sb-doc
465   "Sets the Nth element of List (zero based) to Newval."
466   (do ((count n (1- count))
467        (list list (cdr list)))
468       ((endp list)
469        (error "~S is too large an index for SETF of NTH." n))
470     (declare (fixnum count))
471     (when (<= count 0)
472       (rplaca list newval)
473       (return newval))))
474 \f
475 ;;;; :KEY arg optimization to save funcall of IDENTITY
476
477 ;;; APPLY-KEY saves us a function call sometimes.
478 ;;;    This is not wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
479 ;;;    because this is used in seq.lisp and sort.lisp.
480 (defmacro apply-key (key element)
481   `(if ,key
482        (funcall ,key ,element)
483        ,element))
484
485 (defun identity (thing)
486   #!+sb-doc
487   "Returns what was passed to it."
488   thing)
489
490 (defun complement (function)
491   #!+sb-doc
492   "Builds a new function that returns T whenever FUNCTION returns NIL and
493    NIL whenever FUNCTION returns T."
494   #'(lambda (&optional (arg0 nil arg0-p) (arg1 nil arg1-p) (arg2 nil arg2-p)
495                        &rest more-args)
496       (not (cond (more-args (apply function arg0 arg1 arg2 more-args))
497                  (arg2-p (funcall function arg0 arg1 arg2))
498                  (arg1-p (funcall function arg0 arg1))
499                  (arg0-p (funcall function arg0))
500                  (t (funcall function))))))
501
502 (defun constantly (value &optional (val1 nil val1-p) (val2 nil val2-p)
503                          &rest more-values)
504   #!+sb-doc
505   "Builds a function that always returns VALUE, and posisbly MORE-VALUES."
506   (cond (more-values
507          (let ((list (list* value val1 val2 more-values)))
508            #'(lambda ()
509                (declare (optimize-interface (speed 3) (safety 0)))
510                (values-list list))))
511         (val2-p
512          #'(lambda ()
513              (declare (optimize-interface (speed 3) (safety 0)))
514              (values value val1 val2)))
515         (val1-p
516          #'(lambda ()
517              (declare (optimize-interface (speed 3) (safety 0)))
518              (values value val1)))
519         (t
520          #'(lambda ()
521              (declare (optimize-interface (speed 3) (safety 0)))
522              value))))
523 \f
524 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
525
526 ;;; Use these with the following keyword args:
527 (defmacro with-set-keys (funcall)
528   `(cond ((and testp notp) (error "Test and test-not both supplied."))
529          (notp ,(append funcall '(:key key :test-not test-not)))
530          (t ,(append funcall '(:key key :test test)))))
531
532 (defmacro satisfies-the-test (item elt)
533   (let ((key-tmp (gensym)))
534     `(let ((,key-tmp (apply-key key ,elt)))
535       (cond (testp (funcall test ,item ,key-tmp))
536             (notp (not (funcall test-not ,item ,key-tmp)))
537             (t (funcall test ,item ,key-tmp))))))
538 \f
539 ;;;; substitution of expressions
540
541 (defun subst (new old tree &key key (test #'eql testp) (test-not nil notp))
542   #!+sb-doc
543   "Substitutes new for subtrees matching old."
544   (labels ((s (subtree)
545               (cond ((satisfies-the-test old subtree) new)
546                     ((atom subtree) subtree)
547                     (t (let ((car (s (car subtree)))
548                              (cdr (s (cdr subtree))))
549                          (if (and (eq car (car subtree))
550                                   (eq cdr (cdr subtree)))
551                              subtree
552                              (cons car cdr)))))))
553     (s tree)))
554
555 (defun subst-if (new test tree &key key)
556   #!+sb-doc
557   "Substitutes new for subtrees for which test is true."
558   (labels ((s (subtree)
559               (cond ((funcall test (apply-key key subtree)) new)
560                     ((atom subtree) subtree)
561                     (t (let ((car (s (car subtree)))
562                              (cdr (s (cdr subtree))))
563                          (if (and (eq car (car subtree))
564                                   (eq cdr (cdr subtree)))
565                              subtree
566                              (cons car cdr)))))))
567     (s tree)))
568
569 (defun subst-if-not (new test tree &key key)
570   #!+sb-doc
571   "Substitutes new for subtrees for which test is false."
572   (labels ((s (subtree)
573               (cond ((not (funcall test (apply-key key subtree))) new)
574                     ((atom subtree) subtree)
575                     (t (let ((car (s (car subtree)))
576                              (cdr (s (cdr subtree))))
577                          (if (and (eq car (car subtree))
578                                   (eq cdr (cdr subtree)))
579                              subtree
580                              (cons car cdr)))))))
581     (s tree)))
582
583 (defun nsubst (new old tree &key key (test #'eql testp) (test-not nil notp))
584   #!+sb-doc
585   "Substitutes new for subtrees matching old."
586   (labels ((s (subtree)
587               (cond ((satisfies-the-test old subtree) new)
588                     ((atom subtree) subtree)
589                     (t (do* ((last nil subtree)
590                              (subtree subtree (Cdr subtree)))
591                             ((atom subtree)
592                              (if (satisfies-the-test old subtree)
593                                  (setf (cdr last) new)))
594                          (if (satisfies-the-test old subtree)
595                              (return (setf (cdr last) new))
596                              (setf (car subtree) (s (car subtree)))))
597                        subtree))))
598     (s tree)))
599
600 (defun nsubst-if (new test tree &key key)
601   #!+sb-doc
602   "Substitutes new for subtrees of tree for which test is true."
603   (labels ((s (subtree)
604               (cond ((funcall test (apply-key key subtree)) new)
605                     ((atom subtree) subtree)
606                     (t (do* ((last nil subtree)
607                              (subtree subtree (Cdr subtree)))
608                             ((atom subtree)
609                              (if (funcall test (apply-key key subtree))
610                                  (setf (cdr last) new)))
611                          (if (funcall test (apply-key key subtree))
612                              (return (setf (cdr last) new))
613                              (setf (car subtree) (s (car subtree)))))
614                        subtree))))
615     (s tree)))
616
617 (defun nsubst-if-not (new test tree &key key)
618   #!+sb-doc
619   "Substitutes new for subtrees of tree for which test is false."
620   (labels ((s (subtree)
621               (cond ((not (funcall test (apply-key key subtree))) new)
622                     ((atom subtree) subtree)
623                     (t (do* ((last nil subtree)
624                              (subtree subtree (Cdr subtree)))
625                             ((atom subtree)
626                              (if (not (funcall test (apply-key key subtree)))
627                                  (setf (cdr last) new)))
628                          (if (not (funcall test (apply-key key subtree)))
629                              (return (setf (cdr last) new))
630                              (setf (car subtree) (s (car subtree)))))
631                        subtree))))
632     (s tree)))
633 \f
634 (defun sublis (alist tree &key key (test #'eql) (test-not nil notp))
635   #!+sb-doc
636   "Substitutes from alist into tree nondestructively."
637   (declare (inline assoc))
638   (labels ((s (subtree)
639              (let* ((key-val (apply-key key subtree))
640                     (assoc (if notp
641                                (assoc key-val alist :test-not test-not)
642                                (assoc key-val alist :test test))))
643                (cond (assoc (cdr assoc))
644                      ((atom subtree) subtree)
645                      (t (let ((car (s (car subtree)))
646                               (cdr (s (cdr subtree))))
647                           (if (and (eq car (car subtreE))
648                                    (eq cdr (cdr subtree)))
649                               subtree
650                               (cons car cdr))))))))
651     (s tree)))
652
653 ;;; These are in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
654 ;;; because they can be referenced in inline expansions.
655 (defmacro nsublis-macro ()
656   (let ((key-tmp (gensym)))
657     `(let ((,key-tmp (apply-key key subtree)))
658       (if notp
659           (assoc ,key-tmp alist :test-not test-not)
660           (assoc ,key-tmp alist :test test)))))
661
662 (defun nsublis (alist tree &key key (test #'eql) (test-not nil notp))
663   #!+sb-doc
664   "Substitutes new for subtrees matching old."
665   (declare (inline assoc))
666   (let (temp)
667     (labels ((s (subtree)
668                 (cond ((Setq temp (nsublis-macro))
669                        (cdr temp))
670                       ((atom subtree) subtree)
671                       (t (do* ((last nil subtree)
672                                (subtree subtree (Cdr subtree)))
673                               ((atom subtree)
674                                (if (setq temp (nsublis-macro))
675                                    (setf (cdr last) (cdr temp))))
676                            (if (setq temp (nsublis-macro))
677                                (return (setf (Cdr last) (Cdr temp)))
678                                (setf (car subtree) (s (car subtree)))))
679                          subtree))))
680       (s tree))))
681 \f
682 ;;;; functions for using lists as sets
683
684 (defun member (item list &key key (test #'eql testp) (test-not nil notp))
685   #!+sb-doc
686   "Returns tail of list beginning with first element satisfying EQLity,
687    :test, or :test-not with a given item."
688   (do ((list list (cdr list)))
689       ((null list) nil)
690     (let ((car (car list)))
691       (if (satisfies-the-test item car)
692           (return list)))))
693
694 (defun member-if (test list &key key)
695   #!+sb-doc
696   "Returns tail of list beginning with first element satisfying test(element)"
697   (do ((list list (Cdr list)))
698       ((endp list) nil)
699     (if (funcall test (apply-key key (car list)))
700         (return list))))
701
702 (defun member-if-not (test list &key key)
703   #!+sb-doc
704   "Returns tail of list beginning with first element not satisfying test(el)"
705   (do ((list list (cdr list)))
706       ((endp list) ())
707     (if (not (funcall test (apply-key key (car list))))
708         (return list))))
709
710 (defun tailp (object list)
711   #!+sb-doc
712   "Returns true if Object is the same as some tail of List, otherwise
713    returns false. List must be a proper list or a dotted list."
714   (do ((list list (cdr list)))
715       ((atom list) (eql list object))
716     (if (eql object list)
717         (return t))))
718
719 (defun adjoin (item list &key key (test #'eql) (test-not nil notp))
720   #!+sb-doc
721   "Add item to list unless it is already a member"
722   (declare (inline member))
723   (if (let ((key-val (apply-key key item)))
724         (if notp
725             (member key-val list :test-not test-not :key key)
726             (member key-val list :test test :key key)))
727       list
728       (cons item list)))
729
730 ;;; This function assumes list2 is the result, adding to it from list1 as
731 ;;; necessary. List2 must initialize the result value, so the call to MEMBER
732 ;;; will apply the test to the elements from list1 and list2 in the correct
733 ;;; order.
734 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
735   #!+sb-doc
736   "Returns the union of list1 and list2."
737   (declare (inline member))
738   (when (and testp notp) (error "Test and test-not both supplied."))
739   (let ((res list2))
740     (dolist (elt list1)
741       (unless (with-set-keys (member (apply-key key elt) list2))
742         (push elt res)))
743     res))
744
745 ;;; Destination and source are setf-able and many-evaluable. Sets the source
746 ;;; to the cdr, and "conses" the 1st elt of source to destination.
747 ;;;
748 ;;; FIXME: needs a more mnemonic name
749 (defmacro steve-splice (source destination)
750   `(let ((temp ,source))
751      (setf ,source (cdr ,source)
752            (cdr temp) ,destination
753            ,destination temp)))
754
755 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
756   #!+sb-doc
757   "Destructively returns the union list1 and list2."
758   (declare (inline member))
759   (if (and testp notp)
760       (error "Test and test-not both supplied."))
761   (let ((res list2)
762         (list1 list1))
763     (do ()
764         ((endp list1))
765       (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
766           (steve-splice list1 res)
767           (setf list1 (cdr list1))))
768     res))
769
770 (defun intersection (list1 list2 &key key
771                            (test #'eql testp) (test-not nil notp))
772   #!+sb-doc
773   "Returns the intersection of list1 and list2."
774   (declare (inline member))
775   (if (and testp notp)
776       (error "Test and test-not both supplied."))
777   (let ((res nil))
778     (dolist (elt list1)
779       (if (with-set-keys (member (apply-key key elt) list2))
780           (push elt res)))
781     res))
782
783 (defun nintersection (list1 list2 &key key
784                             (test #'eql testp) (test-not nil notp))
785   #!+sb-doc
786   "Destructively returns the intersection of list1 and list2."
787   (declare (inline member))
788   (if (and testp notp)
789       (error "Test and test-not both supplied."))
790   (let ((res nil)
791         (list1 list1))
792     (do () ((endp list1))
793       (if (with-set-keys (member (apply-key key (car list1)) list2))
794           (steve-splice list1 res)
795           (setq list1 (Cdr list1))))
796     res))
797
798 (defun set-difference (list1 list2 &key key
799                              (test #'eql testp) (test-not nil notp))
800   #!+sb-doc
801   "Returns the elements of list1 which are not in list2."
802   (declare (inline member))
803   (if (and testp notp)
804       (error "Test and test-not both supplied."))
805   (if (null list2)
806       list1
807       (let ((res nil))
808         (dolist (elt list1)
809           (if (not (with-set-keys (member (apply-key key elt) list2)))
810               (push elt res)))
811         res)))
812
813 (defun nset-difference (list1 list2 &key key
814                               (test #'eql testp) (test-not nil notp))
815   #!+sb-doc
816   "Destructively returns the elements of list1 which are not in list2."
817   (declare (inline member))
818   (if (and testp notp)
819       (error "Test and test-not both supplied."))
820   (let ((res nil)
821         (list1 list1))
822     (do () ((endp list1))
823       (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
824           (steve-splice list1 res)
825           (setq list1 (cdr list1))))
826     res))
827
828 (defun set-exclusive-or (list1 list2 &key key
829                                (test #'eql testp) (test-not nil notp))
830   #!+sb-doc
831   "Returns new list of elements appearing exactly once in list1 and list2."
832   (declare (inline member))
833   (let ((result nil))
834     (dolist (elt list1)
835       (unless (with-set-keys (member (apply-key key elt) list2))
836         (setq result (cons elt result))))
837     (dolist (elt list2)
838       (unless (with-set-keys (member (apply-key key elt) list1))
839         (setq result (cons elt result))))
840     result))
841
842 ;;; The outer loop examines list1 while the inner loop examines list2. If an
843 ;;; element is found in list2 "equal" to the element in list1, both are
844 ;;; spliced out. When the end of list1 is reached, what is left of list2 is
845 ;;; tacked onto what is left of list1. The splicing operation ensures that
846 ;;; the correct operation is performed depending on whether splice is at the
847 ;;; top of the list or not
848
849 (defun nset-exclusive-or (list1 list2 &key (test #'eql) (test-not nil notp)
850                                 key)
851   #!+sb-doc
852   "Destructively return a list with elements which appear but once in list1
853    and list2."
854   (do ((list1 list1)
855        (list2 list2)
856        (x list1 (cdr x))
857        (splicex ()))
858       ((endp x)
859        (if (null splicex)
860            (setq list1 list2)
861            (rplacd splicex list2))
862        list1)
863     (do ((y list2 (cdr y))
864          (splicey ()))
865         ((endp y) (setq splicex x))
866       (cond ((let ((key-val-x (apply-key key (car x)))
867                    (key-val-y (apply-key key (Car y))))
868                (if notp
869                    (not (funcall test-not key-val-x key-val-y))
870                    (funcall test key-val-x key-val-y)))
871              (if (null splicex)
872                  (setq list1 (cdr x))
873                  (rplacd splicex (cdr x)))
874              (if (null splicey)
875                  (setq list2 (cdr y))
876                  (rplacd splicey (cdr y)))
877              (return ()))                       ; assume lists are really sets
878             (t (setq splicey y))))))
879
880 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
881   #!+sb-doc
882   "Returns T if every element in list1 is also in list2."
883   (declare (inline member))
884   (dolist (elt list1)
885     (unless (with-set-keys (member (apply-key key elt) list2))
886       (return-from subsetp nil)))
887   T)
888 \f
889 ;;; functions that operate on association lists
890
891 (defun acons (key datum alist)
892   #!+sb-doc
893   "Construct a new alist by adding the pair (key . datum) to alist"
894   (cons (cons key datum) alist))
895
896 (defun pairlis (keys data &optional (alist '()))
897   #!+sb-doc
898   "Construct an association list from keys and data (adding to alist)"
899   (do ((x keys (cdr x))
900        (y data (cdr y)))
901       ((and (endp x) (endp y)) alist)
902     (if (or (endp x) (endp y))
903         (error "The lists of keys and data are of unequal length."))
904     (setq alist (acons (car x) (car y) alist))))
905
906 ;;; This is in the run-time environment (i.e. not wrapped in
907 ;;; EVAL-WHEN (COMPILE EVAL)) because these guys can be inline
908 ;;; expanded.
909 (defmacro assoc-guts (test-guy)
910   `(do ((alist alist (cdr alist)))
911        ((endp alist))
912      ;; FIXME: would be clearer as (WHEN (AND ..) ..)
913      (if (car alist)
914          (if ,test-guy (return (car alist))))))
915
916 (defun assoc (item alist &key key test test-not)
917   #!+sb-doc
918   "Returns the cons in ALIST whose car is equal (by a given test or EQL) to
919    the ITEM."
920   ;; FIXME: Shouldn't there be a check for existence of both TEST and TEST-NOT?
921   (cond (test
922          (if key
923              (assoc-guts (funcall test item (funcall key (caar alist))))
924              (assoc-guts (funcall test item (caar alist)))))
925         (test-not
926          (if key
927              (assoc-guts (not (funcall test-not item
928                                        (funcall key (caar alist)))))
929              (assoc-guts (not (funcall test-not item (caar alist))))))
930         (t
931          (if key
932              (assoc-guts (eql item (funcall key (caar alist))))
933              (assoc-guts (eql item (caar alist)))))))
934
935 (defun assoc-if (predicate alist &key key)
936   #!+sb-doc
937   "Returns the first cons in alist whose car satisfies the Predicate. If
938    key is supplied, apply it to the car of each cons before testing."
939   (if key
940       (assoc-guts (funcall predicate (funcall key (caar alist))))
941       (assoc-guts (funcall predicate (caar alist)))))
942
943 (defun assoc-if-not (predicate alist &key key)
944   #!+sb-doc
945   "Returns the first cons in alist whose car does not satisfiy the Predicate.
946   If key is supplied, apply it to the car of each cons before testing."
947   (if key
948       (assoc-guts (not (funcall predicate (funcall key (caar alist)))))
949       (assoc-guts (not (funcall predicate (caar alist))))))
950
951 (defun rassoc (item alist &key key test test-not)
952   (declare (list alist))
953   #!+sb-doc
954   "Returns the cons in alist whose cdr is equal (by a given test or EQL) to
955    the Item."
956   (cond (test
957          (if key
958              (assoc-guts (funcall test item (funcall key (cdar alist))))
959              (assoc-guts (funcall test item (cdar alist)))))
960         (test-not
961          (if key
962              (assoc-guts (not (funcall test-not item
963                                        (funcall key (cdar alist)))))
964              (assoc-guts (not (funcall test-not item (cdar alist))))))
965         (t
966          (if key
967              (assoc-guts (eql item (funcall key (cdar alist))))
968              (assoc-guts (eql item (cdar alist)))))))
969
970 (defun rassoc-if (predicate alist &key key)
971   #!+sb-doc
972   "Returns the first cons in alist whose cdr satisfies the Predicate. If key
973   is supplied, apply it to the cdr of each cons before testing."
974   (if key
975       (assoc-guts (funcall predicate (funcall key (cdar alist))))
976       (assoc-guts (funcall predicate (cdar alist)))))
977
978 (defun rassoc-if-not (predicate alist &key key)
979   #!+sb-doc
980   "Returns the first cons in alist whose cdr does not satisfy the Predicate.
981   If key is supplied, apply it to the cdr of each cons before testing."
982   (if key
983       (assoc-guts (not (funcall predicate (funcall key (cdar alist)))))
984       (assoc-guts (not (funcall predicate (cdar alist))))))
985 \f
986 ;;;; mapping functions
987
988 (defun map1 (function original-arglists accumulate take-car)
989   #!+sb-doc
990   "This function is called by mapc, mapcar, mapcan, mapl, maplist, and mapcon.
991   It Maps function over the arglists in the appropriate way. It is done when any
992   of the arglists runs out. Until then, it CDRs down the arglists calling the
993   function and accumulating results as desired."
994
995   (let* ((arglists (copy-list original-arglists))
996          (ret-list (list nil))
997          (temp ret-list))
998     (do ((res nil)
999          (args '() '()))
1000         ((dolist (x arglists nil) (if (null x) (return t)))
1001          (if accumulate
1002              (cdr ret-list)
1003              (car original-arglists)))
1004       (do ((l arglists (cdr l)))
1005           ((null l))
1006         (push (if take-car (caar l) (car l)) args)
1007         (setf (car l) (cdar l)))
1008       (setq res (apply function (nreverse args)))
1009       (case accumulate
1010         (:nconc (setq temp (last (nconc temp res))))
1011         (:list (rplacd temp (list res))
1012                (setq temp (cdr temp)))))))
1013
1014 (defun mapc (function list &rest more-lists)
1015   #!+sb-doc
1016   "Applies fn to successive elements of lists, returns its second argument."
1017   (map1 function (cons list more-lists) nil t))
1018
1019 (defun mapcar (function list &rest more-lists)
1020   #!+sb-doc
1021   "Applies fn to successive elements of list, returns list of results."
1022   (map1 function (cons list more-lists) :list t))
1023
1024 (defun mapcan (function list &rest more-lists)
1025   #!+sb-doc
1026   "Applies fn to successive elements of list, returns NCONC of results."
1027   (map1 function (cons list more-lists) :nconc t))
1028
1029 (defun mapl (function list &rest more-lists)
1030   #!+sb-doc
1031   "Applies fn to successive CDRs of list, returns ()."
1032   (map1 function (cons list more-lists) nil nil))
1033
1034 (defun maplist (function list &rest more-lists)
1035   #!+sb-doc
1036   "Applies fn to successive CDRs of list, returns list of results."
1037   (map1 function (cons list more-lists) :list nil))
1038
1039 (defun mapcon (function list &rest more-lists)
1040   #!+sb-doc
1041   "Applies fn to successive CDRs of lists, returns NCONC of results."
1042   (map1 function (cons list more-lists) :nconc nil))