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