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