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