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