da6ca8e60a30b7c9c8b17894fe4dd9b973dc37f7
[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 make-list
22           tailp union
23           nunion intersection nintersection set-difference nset-difference
24           set-exclusive-or nset-exclusive-or subsetp acons
25           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 ;;; LAST
234 ;;;
235 ;;; Transforms in src/compiler/srctran.lisp pick the most specific
236 ;;; version possible. %LAST/BIGNUM is admittedly somewhat academic...
237 (macrolet ((last0-macro ()
238              `(let ((rest list)
239                     (list list))
240                 (loop (unless (consp rest)
241                         (return rest))
242                   (shiftf list rest (cdr rest)))))
243            (last1-macro ()
244              `(let ((rest list)
245                     (list list))
246                 (loop (unless (consp rest)
247                         (return list))
248                   (shiftf list rest (cdr rest)))))
249            (lastn-macro (type)
250              `(let ((returned-list list)
251                     (checked-list list)
252                     (n (truly-the ,type n)))
253                 (declare (,type n))
254                 (tagbody
255                  :scan
256                    (pop checked-list)
257                    (when (atom checked-list)
258                      (go :done))
259                    (if (zerop (truly-the ,type (decf n)))
260                        (go :pop)
261                        (go :scan))
262                  :pop
263                    (pop returned-list)
264                    (pop checked-list)
265                    (if (atom checked-list)
266                        (go :done)
267                        (go :pop))
268                  :done)
269                 returned-list)))
270
271   (defun %last0 (list)
272     (declare (optimize speed (sb!c::verify-arg-count 0)))
273     (last0-macro))
274
275   (defun %last1 (list)
276     (declare (optimize speed (sb!c::verify-arg-count 0)))
277     (last1-macro))
278
279   (defun %lastn/fixnum (list n)
280     (declare (optimize speed (sb!c::verify-arg-count 0))
281              (type (and unsigned-byte fixnum) n))
282     (case n
283       (1 (last1-macro))
284       (0 (last0-macro))
285       (t (lastn-macro fixnum))))
286
287   (defun %lastn/bignum (list n)
288     (declare (optimize speed (sb!c::verify-arg-count 0))
289              (type (and unsigned-byte bignum) n))
290     (lastn-macro unsigned-byte))
291
292   (defun last (list &optional (n 1))
293     #!+sb-doc
294     "Return the last N conses (not the last element!) of a list."
295     (case n
296       (1 (last1-macro))
297       (0 (last0-macro))
298       (t
299        (typecase n
300          (fixnum
301           (lastn-macro fixnum))
302          (bignum
303           (lastn-macro unsigned-byte)))))))
304
305 (define-compiler-macro last (&whole form list &optional (n 1) &environment env)
306   (if (sb!xc:constantp n env)
307       (case (constant-form-value n env)
308         (0 `(%last0 ,list))
309         (1 `(%last1 ,list))
310         (t form))
311       form))
312
313 (defun list (&rest args)
314   #!+sb-doc
315   "Return constructs and returns a list of its arguments."
316   args)
317
318 ;;; LIST* is done the same as LIST, except that the last cons is made
319 ;;; a dotted pair.
320
321 (defun list* (arg &rest others)
322   #!+sb-doc
323   "Return a list of the arguments with last cons a dotted pair."
324   ;; We know the &REST is a proper list.
325   (declare (optimize (sb!c::type-check 0)))
326   (cond ((atom others) arg)
327         ((atom (cdr others)) (cons arg (car others)))
328         (t (do ((x others (cdr x)))
329                ((null (cddr x)) (rplacd x (cadr x))))
330            (cons arg others))))
331
332 (defun make-list (size &key initial-element)
333   #!+sb-doc
334   "Constructs a list with size elements each set to value"
335   (declare (type index size))
336   (do ((count size (1- count))
337        (result '() (cons initial-element result)))
338       ((<= count 0) result)
339     (declare (type index count))))
340 \f
341 (defun append (&rest lists)
342   #!+sb-doc
343   "Construct a new list by concatenating the list arguments"
344   (declare (truly-dynamic-extent lists) (optimize speed))
345   (labels ((fail (object)
346              (error 'type-error
347                     :datum object
348                     :expected-type 'list))
349            (append-into (last-cons current rest)
350              ;; Set (CDR LAST-CONS) to (APPLY #'APPEND CURRENT REST).
351              (declare (cons last-cons rest))
352              (if (listp current)
353                  (if (consp current)
354                      ;; normal case, cdr down the list
355                      (append-into (setf (cdr last-cons) (list (car current)))
356                                   (cdr current)
357                                   rest)
358                      ;; empty list
359                      (let ((more (cdr rest)))
360                        (if (null more)
361                            (setf (cdr last-cons) (car rest))
362                            (append-into last-cons (car rest) more))))
363                  (fail current)))
364            (append1 (lists)
365              (let ((current (car lists))
366                    (rest (cdr lists)))
367                (cond ((null rest)
368                       current)
369                      ((consp current)
370                       (let ((result (truly-the cons (list (car current)))))
371                         (append-into result
372                                      (cdr current)
373                                      rest)
374                         result))
375                      ((null current)
376                       (append1 rest))
377                      (t
378                       (fail current))))))
379     (append1 lists)))
380
381 (defun append2 (x y)
382   (declare (optimize speed (sb!c::verify-arg-count 0)))
383   (if (null x)
384       y
385       (let ((result (list (car x))))
386         (do ((more (cdr x) (cdr more))
387              (tail result (cdr tail)))
388             ((null more)
389              (rplacd tail y)
390              result)
391           (rplacd tail (list (car more)))))))
392
393 (define-compiler-macro append (&whole form &rest lists)
394   (case (length lists)
395     (0 nil)
396     (1 (car lists))
397     (2 `(append2 ,@lists))
398     (t form)))
399 \f
400 ;;;; list copying functions
401
402 (eval-when (:compile-toplevel :load-toplevel :execute)
403   (sb!xc:defmacro !copy-list-macro (list &key check-proper-list)
404     ;; Unless CHECK-PROPER-LIST is true, the list is copied correctly
405     ;; even if the list is not terminated by NIL. The new list is built
406     ;; by CDR'ing SPLICE which is always at the tail of the new list.
407     `(when ,list
408        (let ((copy (list (car ,list))))
409          (do ((orig (cdr ,list) (cdr orig))
410               (splice copy (cdr (rplacd splice (cons (car orig) nil)))))
411              (,@(if check-proper-list
412                     '((endp orig))
413                     '((atom orig)
414                       (unless (null orig)
415                         (rplacd splice orig))))
416               copy))))))
417
418 (defun copy-list (list)
419   #!+sb-doc
420   "Return a new list which is EQUAL to LIST. LIST may be improper."
421   (!copy-list-macro list))
422
423 (defun copy-alist (alist)
424   #!+sb-doc
425   "Return a new association list which is EQUAL to ALIST."
426   (if (endp alist)
427       alist
428       (let ((result
429              (cons (if (atom (car alist))
430                        (car alist)
431                        (cons (caar alist) (cdar alist)))
432                    nil)))
433         (do ((x (cdr alist) (cdr x))
434              (splice result
435                      (cdr (rplacd splice
436                                   (cons
437                                    (if (atom (car x))
438                                        (car x)
439                                        (cons (caar x) (cdar x)))
440                                    nil)))))
441             ((endp x)))
442         result)))
443
444 (defun copy-tree (object)
445   #!+sb-doc
446   "Recursively copy trees of conses."
447   (if (consp object)
448       (let ((result (list (if (consp (car object))
449                               (copy-tree (car object))
450                               (car object)))))
451         (loop for last-cons = result then new-cons
452               for cdr = (cdr object) then (cdr cdr)
453               for car = (if (consp cdr)
454                             (car cdr)
455                             (return (setf (cdr last-cons) cdr)))
456               for new-cons = (list (if (consp car)
457                                        (copy-tree car)
458                                        car))
459               do (setf (cdr last-cons) new-cons))
460         result)
461       object))
462
463 \f
464 ;;;; more commonly-used list functions
465
466 (defun revappend (x y)
467   #!+sb-doc
468   "Return (append (reverse x) y)."
469   (do ((top x (cdr top))
470        (result y (cons (car top) result)))
471       ((endp top) result)))
472
473 ;;; NCONC finds the first non-null list, so it can make splice point
474 ;;; to a cons. After finding the first cons element, it holds it in a
475 ;;; result variable while running down successive elements tacking
476 ;;; them together. While tacking lists together, if we encounter a
477 ;;; null list, we set the previous list's last cdr to nil just in case
478 ;;; it wasn't already nil, and it could have been dotted while the
479 ;;; null list was the last argument to NCONC. The manipulation of
480 ;;; splice (that is starting it out on a first cons, setting LAST of
481 ;;; splice, and setting splice to ele) inherently handles (nconc x x),
482 ;;; and it avoids running down the last argument to NCONC which allows
483 ;;; the last argument to be circular.
484 (defun nconc (&rest lists)
485    #!+sb-doc
486    "Concatenates the lists given as arguments (by changing them)"
487    (declare (truly-dynamic-extent lists) (optimize speed))
488    (flet ((fail (object)
489             (error 'type-error
490                    :datum object
491                    :expected-type 'list)))
492      (do ((top lists (cdr top)))
493          ((null top) nil)
494        (let ((top-of-top (car top)))
495          (typecase top-of-top
496            (cons
497             (let* ((result top-of-top)
498                    (splice result))
499               (do ((elements (cdr top) (cdr elements)))
500                   ((endp elements))
501                 (let ((ele (car elements)))
502                   (typecase ele
503                     (cons (rplacd (last splice) ele)
504                           (setf splice ele))
505                     (null (rplacd (last splice) nil))
506                     (atom (if (cdr elements)
507                               (fail ele)
508                               (rplacd (last splice) ele))))))
509               (return result)))
510            (null)
511            (atom
512             (if (cdr top)
513                 (fail top-of-top)
514                 (return top-of-top))))))))
515
516 (defun nreconc (x y)
517   #!+sb-doc
518   "Return (NCONC (NREVERSE X) Y)."
519   (do ((1st (cdr x) (if (endp 1st) 1st (cdr 1st)))
520        (2nd x 1st)              ;2nd follows first down the list.
521        (3rd y 2nd))             ;3rd follows 2nd down the list.
522       ((atom 2nd) 3rd)
523     (rplacd 2nd 3rd)))
524 \f
525 (flet (;; Return the number of conses at the head of the
526        ;; possibly-improper list LIST. (Or if LIST is circular, you
527        ;; lose.)
528        (count-conses (list)
529          (do ((in-list list (cdr in-list))
530               (result 0 (1+ result)))
531              ((atom in-list)
532               result)
533            (declare (type index result)))))
534   (declare (ftype (function (t) index) count-conses))
535   (defun butlast (list &optional (n 1))
536     (if (typep n 'index)
537         (let ((n-conses-in-list (count-conses list)))
538           (cond ((zerop n)
539                  ;; (We can't use SUBSEQ in this case because LIST isn't
540                  ;; necessarily a proper list, but SUBSEQ expects a
541                  ;; proper sequence. COPY-LIST isn't so fussy.)
542                  (copy-list list))
543                 ((>= n n-conses-in-list)
544                  nil)
545                 (t
546                  ;; (LIST isn't necessarily a proper list in this case
547                  ;; either, and technically SUBSEQ wants a proper
548                  ;; sequence, but no reasonable implementation of SUBSEQ
549                  ;; will actually walk down to the end of the list to
550                  ;; check, and since we're calling our own implementation
551                  ;; we know it's reasonable, so it's OK.)
552                  (subseq list 0 (- n-conses-in-list n)))))
553         nil))
554   (defun nbutlast (list &optional (n 1))
555     (cond ((zerop n)
556            list)
557           ((not (typep n 'index))
558            nil)
559           (t (let ((n-conses-in-list (count-conses list)))
560                (unless (<= n-conses-in-list n)
561                  (setf (cdr (nthcdr (- n-conses-in-list n 1) list))
562                        nil)
563                  list))))))
564
565 (defun ldiff (list object)
566   "Return a new list, whose elements are those of LIST that appear before
567    OBJECT. If OBJECT is not a tail of LIST, a copy of LIST is returned.
568    LIST must be a proper list or a dotted list."
569   (do* ((list list (cdr list))
570         (result (list ()))
571         (splice result))
572        ((atom list)
573         (if (eql list object)
574             (cdr result)
575             (progn (rplacd splice list) (cdr result))))
576     (if (eql list object)
577         (return (cdr result))
578         (setq splice (cdr (rplacd splice (list (car list))))))))
579 \f
580 ;;;; functions to alter list structure
581
582 (defun rplaca (cons x)
583   #!+sb-doc
584   "Change the CAR of CONS to X and return the CONS."
585   (rplaca cons x))
586
587 (defun rplacd (cons x)
588   #!+sb-doc
589   "Change the CDR of CONS to X and return the CONS."
590   (rplacd cons x))
591
592 ;;; The following are for use by SETF.
593
594 (defun %rplaca (x val) (rplaca x val) val)
595
596 (defun %rplacd (x val) (rplacd x val) val)
597
598 ;;; Set the Nth element of LIST to NEWVAL.
599 (defun %setnth (n list newval)
600   (typecase n
601     (index
602      (do ((count n (1- count))
603           (list list (cdr list)))
604          ((endp list)
605           (error "~S is too large an index for SETF of NTH." n))
606        (declare (type fixnum count))
607        (when (<= count 0)
608          (rplaca list newval)
609          (return newval))))
610     (t (let ((cons (nthcdr n list)))
611          (when (endp cons)
612            (error "~S is too large an index for SETF of NTH." n))
613          (rplaca cons newval)
614          newval))))
615 \f
616 ;;;; :KEY arg optimization to save funcall of IDENTITY
617
618 ;;; APPLY-KEY saves us a function call sometimes.
619 ;;;    This isn't wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
620 ;;;    because it's used in seq.lisp and sort.lisp.
621 (defmacro apply-key (key element)
622   `(if ,key
623        (funcall ,key ,element)
624        ,element))
625 \f
626 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
627
628 ;;; Use these with the following &KEY args:
629 (defmacro with-set-keys (funcall)
630   `(if notp
631        ,(append funcall '(:key key :test-not test-not))
632        ,(append funcall '(:key key :test test))))
633
634 (defmacro satisfies-the-test (item elt)
635   (let ((key-tmp (gensym)))
636     `(let ((,key-tmp (apply-key key ,elt)))
637       (cond (testp (funcall test ,item ,key-tmp))
638             (notp (not (funcall test-not ,item ,key-tmp)))
639             (t (funcall test ,item ,key-tmp))))))
640 \f
641 ;;;; substitution of expressions
642
643 (defun subst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
644   #!+sb-doc
645   "Substitutes new for subtrees matching old."
646   (when (and testp notp)
647     (error ":TEST and :TEST-NOT were both supplied."))
648   (let ((key (and key (%coerce-callable-to-fun key)))
649         (test (if testp (%coerce-callable-to-fun test) test))
650         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
651     (declare (type function test test-not))
652     (labels ((s (subtree)
653                (cond ((satisfies-the-test old subtree) new)
654                      ((atom subtree) subtree)
655                      (t (let ((car (s (car subtree)))
656                               (cdr (s (cdr subtree))))
657                           (if (and (eq car (car subtree))
658                                    (eq cdr (cdr subtree)))
659                               subtree
660                               (cons car cdr)))))))
661       (s tree))))
662
663 (defun subst-if (new test tree &key key)
664   #!+sb-doc
665   "Substitutes new for subtrees for which test is true."
666   (let ((test (%coerce-callable-to-fun test))
667         (key (and key (%coerce-callable-to-fun key))))
668     (labels ((s (subtree)
669                (cond ((funcall test (apply-key key subtree)) new)
670                      ((atom subtree) subtree)
671                      (t (let ((car (s (car subtree)))
672                               (cdr (s (cdr subtree))))
673                           (if (and (eq car (car subtree))
674                                    (eq cdr (cdr subtree)))
675                               subtree
676                               (cons car cdr)))))))
677       (s tree))))
678
679 (defun subst-if-not (new test tree &key key)
680   #!+sb-doc
681   "Substitutes new for subtrees for which test is false."
682   (let ((test (%coerce-callable-to-fun test))
683         (key (and key (%coerce-callable-to-fun key))))
684     (labels ((s (subtree)
685                (cond ((not (funcall test (apply-key key subtree))) new)
686                      ((atom subtree) subtree)
687                      (t (let ((car (s (car subtree)))
688                               (cdr (s (cdr subtree))))
689                           (if (and (eq car (car subtree))
690                                    (eq cdr (cdr subtree)))
691                               subtree
692                               (cons car cdr)))))))
693       (s tree))))
694
695 (defun nsubst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
696   #!+sb-doc
697   "Substitute NEW for subtrees matching OLD."
698   (when (and testp notp)
699     (error ":TEST and :TEST-NOT were both supplied."))
700   (let ((key (and key (%coerce-callable-to-fun key)))
701         (test (if testp (%coerce-callable-to-fun test) test))
702         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
703     (declare (type function test test-not))
704     (labels ((s (subtree)
705                (cond ((satisfies-the-test old subtree) new)
706                      ((atom subtree) subtree)
707                      (t (do* ((last nil subtree)
708                               (subtree subtree (cdr subtree)))
709                              ((atom subtree)
710                               (if (satisfies-the-test old subtree)
711                                   (setf (cdr last) new)))
712                           (if (satisfies-the-test old subtree)
713                               (return (setf (cdr last) new))
714                               (setf (car subtree) (s (car subtree)))))
715                         subtree))))
716       (s tree))))
717
718 (defun nsubst-if (new test tree &key key)
719   #!+sb-doc
720   "Substitute NEW for subtrees of TREE for which TEST is true."
721   (let ((test (%coerce-callable-to-fun test))
722         (key (and key (%coerce-callable-to-fun key))))
723     (labels ((s (subtree)
724                (cond ((funcall test (apply-key key subtree)) new)
725                      ((atom subtree) subtree)
726                      (t (do* ((last nil subtree)
727                               (subtree subtree (cdr subtree)))
728                              ((atom subtree)
729                               (if (funcall test (apply-key key subtree))
730                                   (setf (cdr last) new)))
731                           (if (funcall test (apply-key key subtree))
732                               (return (setf (cdr last) new))
733                               (setf (car subtree) (s (car subtree)))))
734                         subtree))))
735       (s tree))))
736
737 (defun nsubst-if-not (new test tree &key key)
738   #!+sb-doc
739   "Substitute NEW for subtrees of TREE for which TEST is false."
740   (let ((test (%coerce-callable-to-fun test))
741         (key (and key (%coerce-callable-to-fun key))))
742     (labels ((s (subtree)
743                (cond ((not (funcall test (apply-key key subtree))) new)
744                      ((atom subtree) subtree)
745                      (t (do* ((last nil subtree)
746                               (subtree subtree (cdr subtree)))
747                              ((atom subtree)
748                               (if (not (funcall test (apply-key key subtree)))
749                                   (setf (cdr last) new)))
750                           (if (not (funcall test (apply-key key subtree)))
751                               (return (setf (cdr last) new))
752                               (setf (car subtree) (s (car subtree)))))
753                         subtree))))
754       (s tree))))
755 \f
756 (defun sublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
757   #!+sb-doc
758   "Substitute from ALIST into TREE nondestructively."
759   (when (and testp notp)
760     (error ":TEST and :TEST-NOT were both supplied."))
761   (let ((key (and key (%coerce-callable-to-fun key)))
762         (test (if testp (%coerce-callable-to-fun test) test))
763         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
764     (declare (type function test test-not))
765     (declare (inline assoc))
766     (labels ((s (subtree)
767                (let* ((key-val (apply-key key subtree))
768                       (assoc (if notp
769                                  (assoc key-val alist :test-not test-not)
770                                  (assoc key-val alist :test test))))
771                  (cond (assoc (cdr assoc))
772                        ((atom subtree) subtree)
773                        (t (let ((car (s (car subtree)))
774                                 (cdr (s (cdr subtree))))
775                             (if (and (eq car (car subtree))
776                                      (eq cdr (cdr subtree)))
777                                 subtree
778                                 (cons car cdr))))))))
779       (s tree))))
780
781 ;;; This is in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
782 ;;; because it can be referenced in inline expansions.
783 (defmacro nsublis-macro ()
784   (let ((key-tmp (gensym)))
785     `(let ((,key-tmp (apply-key key subtree)))
786       (if notp
787           (assoc ,key-tmp alist :test-not test-not)
788           (assoc ,key-tmp alist :test test)))))
789
790 (defun nsublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
791   #!+sb-doc
792   "Substitute from ALIST into TRUE destructively."
793   (when (and testp notp)
794     (error ":TEST and :TEST-NOT were both supplied."))
795   (let ((key (and key (%coerce-callable-to-fun key)))
796         (test (if testp (%coerce-callable-to-fun test) test))
797         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
798     (declare (inline assoc))
799     (let (temp)
800       (labels ((s (subtree)
801                  (cond ((setq temp (nsublis-macro))
802                         (cdr temp))
803                        ((atom subtree) subtree)
804                        (t (do* ((last nil subtree)
805                                 (subtree subtree (cdr subtree)))
806                                ((atom subtree)
807                                 (if (setq temp (nsublis-macro))
808                                     (setf (cdr last) (cdr temp))))
809                             (if (setq temp (nsublis-macro))
810                                 (return (setf (cdr last) (cdr temp)))
811                                 (setf (car subtree) (s (car subtree)))))
812                           subtree))))
813         (s tree)))))
814 \f
815 ;;;; functions for using lists as sets
816
817 (defun member (item list &key key (test nil testp) (test-not nil notp))
818   #!+sb-doc
819   "Return the tail of LIST beginning with first element satisfying EQLity,
820    :TEST, or :TEST-NOT with the given ITEM."
821   (when (and testp notp)
822     (error ":TEST and :TEST-NOT were both supplied."))
823   (let ((key (and key (%coerce-callable-to-fun key)))
824         (test (and testp (%coerce-callable-to-fun test)))
825         (test-not (and notp (%coerce-callable-to-fun test-not))))
826     (cond (test
827            (if key
828                (%member-key-test item list key test)
829                (%member-test item list test)))
830           (test-not
831            (if key
832                (%member-key-test-not item list key test-not)
833                (%member-test-not item list test-not)))
834           (t
835            (if key
836                (%member-key item list key)
837                (%member item list))))))
838
839 (defun member-if (test list &key key)
840   #!+sb-doc
841   "Return tail of LIST beginning with first element satisfying TEST."
842   (let ((test (%coerce-callable-to-fun test))
843         (key (and key (%coerce-callable-to-fun key))))
844     (if key
845         (%member-if-key test list key)
846         (%member-if test list))))
847
848 (defun member-if-not (test list &key key)
849   #!+sb-doc
850   "Return tail of LIST beginning with first element not satisfying TEST."
851   (let ((test (%coerce-callable-to-fun test))
852         (key (and key (%coerce-callable-to-fun key))))
853     (if key
854         (%member-if-not-key test list key)
855         (%member-if-not test list))))
856
857 (defun tailp (object list)
858   #!+sb-doc
859   "Return true if OBJECT is the same as some tail of LIST, otherwise
860    returns false. LIST must be a proper list or a dotted list."
861   (do ((list list (cdr list)))
862       ((atom list) (eql list object))
863     (if (eql object list)
864         (return t))))
865
866 (defun adjoin (item list &key key (test #'eql testp) (test-not nil notp))
867   #!+sb-doc
868   "Add ITEM to LIST unless it is already a member"
869   (when (and testp notp)
870     (error ":TEST and :TEST-NOT were both supplied."))
871   (let ((key (and key (%coerce-callable-to-fun key)))
872         (test (and testp (%coerce-callable-to-fun test)))
873         (test-not (and notp (%coerce-callable-to-fun test-not))))
874     (cond (test
875            (if key
876                (%adjoin-key-test item list key test)
877                (%adjoin-test item list test)))
878           (test-not
879            (if key
880                (%adjoin-key-test-not item list key test-not)
881                (%adjoin-test-not item list test-not)))
882           (t
883            (if key
884                (%adjoin-key item list key)
885                (%adjoin item list))))))
886
887 (defconstant +list-based-union-limit+ 80)
888
889 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
890   #!+sb-doc
891   "Return the union of LIST1 and LIST2."
892   (declare (inline member))
893   (when (and testp notp)
894     (error ":TEST and :TEST-NOT were both supplied."))
895   ;; We have two possibilities here: for shortish lists we pick up the
896   ;; shorter one as the result, and add the other one to it. For long
897   ;; lists we use a hash-table when possible.
898   (let ((n1 (length list1))
899         (n2 (length list2))
900         (key (and key (%coerce-callable-to-fun key)))
901         (test (if notp
902                   (let ((test-not-fun (%coerce-callable-to-fun test-not)))
903                     (lambda (x y) (not (funcall test-not-fun x y))))
904                   (%coerce-callable-to-fun test))))
905     (multiple-value-bind (short long n-short)
906         (if (< n1 n2)
907             (values list1 list2 n1)
908             (values list2 list1 n2))
909       (if (or (< n-short +list-based-union-limit+)
910               (not (member test (list #'eq #'eql #'equal #'equalp))))
911           (let ((orig short))
912             (dolist (elt long)
913               (unless (member (apply-key key elt) orig :key key :test test)
914                 (push elt short)))
915             short)
916           (let ((table (make-hash-table :test test :size (+ n1 n2)))
917                 (union nil))
918             (dolist (elt long)
919               (setf (gethash (apply-key key elt) table) elt))
920             (dolist (elt short)
921               (setf (gethash (apply-key key elt) table) elt))
922             (maphash (lambda (k v)
923                        (declare (ignore k))
924                        (push v union))
925                      table)
926             union)))))
927
928 ;;; Destination and source are SETF-able and many-evaluable. Set the
929 ;;; SOURCE to the CDR, and "cons" the 1st elt of source to DESTINATION.
930 ;;;
931 ;;; FIXME: needs a more mnemonic name
932 (defmacro steve-splice (source destination)
933   `(let ((temp ,source))
934      (setf ,source (cdr ,source)
935            (cdr temp) ,destination
936            ,destination temp)))
937
938 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
939   #!+sb-doc
940   "Destructively return the union of LIST1 and LIST2."
941   (declare (inline member))
942   (when (and testp notp)
943     (error ":TEST and :TEST-NOT were both supplied."))
944   ;; We have two possibilities here: for shortish lists we pick up the
945   ;; shorter one as the result, and add the other one to it. For long
946   ;; lists we use a hash-table when possible.
947   (let ((n1 (length list1))
948         (n2 (length list2))
949         (key (and key (%coerce-callable-to-fun key)))
950         (test (if notp
951                   (let ((test-not-fun (%coerce-callable-to-fun test-not)))
952                     (lambda (x y) (not (funcall test-not-fun x y))))
953                   (%coerce-callable-to-fun test))))
954     (multiple-value-bind (short long n-short)
955         (if (< n1 n2)
956             (values list1 list2 n1)
957             (values list2 list1 n2))
958       (if (or (< n-short +list-based-union-limit+)
959               (not (member test (list #'eq #'eql #'equal #'equalp))))
960           (let ((orig short))
961             (do ((elt (car long) (car long)))
962                 ((endp long))
963               (if (not (member (apply-key key elt) orig :key key :test test))
964                   (steve-splice long short)
965                   (setf long (cdr long))))
966             short)
967           (let ((table (make-hash-table :test test :size (+ n1 n2))))
968             (dolist (elt long)
969               (setf (gethash (apply-key key elt) table) elt))
970             (dolist (elt short)
971               (setf (gethash (apply-key key elt) table) elt))
972             (let ((union long)
973                   (head long))
974               (maphash (lambda (k v)
975                          (declare (ignore k))
976                          (if head
977                              (setf (car head) v
978                                    head (cdr head))
979                              (push v union)))
980                       table)
981               union))))))
982
983 (defun intersection (list1 list2
984                      &key key (test #'eql testp) (test-not nil notp))
985   #!+sb-doc
986   "Return the intersection of LIST1 and LIST2."
987   (declare (inline member))
988   (when (and testp notp)
989     (error ":TEST and :TEST-NOT were both supplied."))
990   (let ((key (and key (%coerce-callable-to-fun key))))
991     (let ((res nil))
992       (dolist (elt list1)
993         (if (with-set-keys (member (apply-key key elt) list2))
994             (push elt res)))
995       res)))
996
997 (defun nintersection (list1 list2
998                       &key key (test #'eql testp) (test-not nil notp))
999   #!+sb-doc
1000   "Destructively return the intersection of LIST1 and LIST2."
1001   (declare (inline member))
1002   (when (and testp notp)
1003     (error ":TEST and :TEST-NOT were both supplied."))
1004   (let ((key (and key (%coerce-callable-to-fun key))))
1005     (let ((res nil)
1006           (list1 list1))
1007       (do () ((endp list1))
1008         (if (with-set-keys (member (apply-key key (car list1)) list2))
1009             (steve-splice list1 res)
1010             (setq list1 (cdr list1))))
1011       res)))
1012
1013 (defun set-difference (list1 list2
1014                        &key key (test #'eql testp) (test-not nil notp))
1015   #!+sb-doc
1016   "Return the elements of LIST1 which are not in LIST2."
1017   (declare (inline member))
1018   (when (and testp notp)
1019     (error ":TEST and :TEST-NOT were both supplied."))
1020   (let ((key (and key (%coerce-callable-to-fun key))))
1021     (if (null list2)
1022         list1
1023         (let ((res nil))
1024           (dolist (elt list1)
1025             (if (not (with-set-keys (member (apply-key key elt) list2)))
1026                 (push elt res)))
1027           res))))
1028
1029 (defun nset-difference (list1 list2
1030                         &key key (test #'eql testp) (test-not nil notp))
1031   #!+sb-doc
1032   "Destructively return the elements of LIST1 which are not in LIST2."
1033   (declare (inline member))
1034   (when (and testp notp)
1035     (error ":TEST and :TEST-NOT were both supplied."))
1036   (let ((key (and key (%coerce-callable-to-fun key))))
1037     (let ((res nil)
1038           (list1 list1))
1039       (do () ((endp list1))
1040         (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
1041             (steve-splice list1 res)
1042             (setq list1 (cdr list1))))
1043       res)))
1044
1045 (defun set-exclusive-or (list1 list2
1046                          &key key (test #'eql testp) (test-not #'eql notp))
1047   #!+sb-doc
1048   "Return new list of elements appearing exactly once in LIST1 and LIST2."
1049   (declare (inline member))
1050   (when (and testp notp)
1051     (error ":TEST and :TEST-NOT were both supplied."))
1052   (let ((result nil)
1053         (key (and key (%coerce-callable-to-fun key)))
1054         (test (if testp (%coerce-callable-to-fun test) test))
1055         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
1056     (declare (type function test test-not))
1057     (dolist (elt list1)
1058       (unless (with-set-keys (member (apply-key key elt) list2))
1059         (setq result (cons elt result))))
1060     (let ((test (if testp
1061                     (lambda (x y) (funcall test y x))
1062                     test))
1063           (test-not (if notp
1064                         (lambda (x y) (funcall test-not y x))
1065                         test-not)))
1066       (dolist (elt list2)
1067         (unless (with-set-keys (member (apply-key key elt) list1))
1068           (setq result (cons elt result)))))
1069     result))
1070
1071 (defun nset-exclusive-or (list1 list2
1072                           &key key (test #'eql testp) (test-not #'eql notp))
1073   #!+sb-doc
1074   "Destructively return a list with elements which appear but once in LIST1
1075    and LIST2."
1076   (when (and testp notp)
1077     (error ":TEST and :TEST-NOT were both supplied."))
1078   (let ((key (and key (%coerce-callable-to-fun key)))
1079         (test (if testp (%coerce-callable-to-fun test) test))
1080         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
1081     (declare (type function test test-not))
1082     ;; The outer loop examines LIST1 while the inner loop examines
1083     ;; LIST2. If an element is found in LIST2 "equal" to the element
1084     ;; in LIST1, both are spliced out. When the end of LIST1 is
1085     ;; reached, what is left of LIST2 is tacked onto what is left of
1086     ;; LIST1. The splicing operation ensures that the correct
1087     ;; operation is performed depending on whether splice is at the
1088     ;; top of the list or not.
1089     (do ((list1 list1)
1090          (list2 list2)
1091          (x list1 (cdr x))
1092          (splicex ())
1093          (deleted-y ())
1094          ;; elements of LIST2, which are "equal" to some processed
1095          ;; earlier elements of LIST1
1096          )
1097         ((endp x)
1098          (if (null splicex)
1099              (setq list1 list2)
1100              (rplacd splicex list2))
1101          list1)
1102       (let ((key-val-x (apply-key key (car x)))
1103             (found-duplicate nil))
1104
1105         ;; Move all elements from LIST2, which are "equal" to (CAR X),
1106         ;; to DELETED-Y.
1107         (do* ((y list2 next-y)
1108               (next-y (cdr y) (cdr y))
1109               (splicey ()))
1110              ((endp y))
1111           (cond ((let ((key-val-y (apply-key key (car y))))
1112                    (if notp
1113                        (not (funcall test-not key-val-x key-val-y))
1114                        (funcall test key-val-x key-val-y)))
1115                  (if (null splicey)
1116                      (setq list2 (cdr y))
1117                      (rplacd splicey (cdr y)))
1118                  (setq deleted-y (rplacd y deleted-y))
1119                  (setq found-duplicate t))
1120                 (t (setq splicey y))))
1121
1122         (unless found-duplicate
1123           (setq found-duplicate (with-set-keys (member key-val-x deleted-y))))
1124
1125         (if found-duplicate
1126             (if (null splicex)
1127                 (setq list1 (cdr x))
1128                 (rplacd splicex (cdr x)))
1129             (setq splicex x))))))
1130
1131 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
1132   #!+sb-doc
1133   "Return T if every element in LIST1 is also in LIST2."
1134   (declare (inline member))
1135   (when (and testp notp)
1136     (error ":TEST and :TEST-NOT were both supplied."))
1137   (let ((key (and key (%coerce-callable-to-fun key))))
1138     (dolist (elt list1)
1139       (unless (with-set-keys (member (apply-key key elt) list2))
1140         (return-from subsetp nil)))
1141     t))
1142 \f
1143 ;;;; functions that operate on association lists
1144
1145 (defun acons (key datum alist)
1146   #!+sb-doc
1147   "Construct a new alist by adding the pair (KEY . DATUM) to ALIST."
1148   (cons (cons key datum) alist))
1149
1150 (defun pairlis (keys data &optional (alist '()))
1151   #!+sb-doc
1152   "Construct an association list from KEYS and DATA (adding to ALIST)."
1153   (do ((x keys (cdr x))
1154        (y data (cdr y)))
1155       ((and (endp x) (endp y)) alist)
1156     (if (or (endp x) (endp y))
1157         (error "The lists of keys and data are of unequal length."))
1158     (setq alist (acons (car x) (car y) alist))))
1159
1160 (defun assoc (item alist &key key (test nil testp) (test-not nil notp))
1161   #!+sb-doc
1162   "Return the cons in ALIST whose car is equal (by a given test or EQL) to
1163    the ITEM."
1164   (when (and testp notp)
1165     (error ":TEST and :TEST-NOT were both supplied."))
1166   (let ((key (and key (%coerce-callable-to-fun key)))
1167         (test (and testp (%coerce-callable-to-fun test)))
1168         (test-not (and notp (%coerce-callable-to-fun test-not))))
1169     (cond (test
1170            (if key
1171                (%assoc-key-test item alist key test)
1172                (%assoc-test item alist test)))
1173           (test-not
1174            (if key
1175                (%assoc-key-test-not item alist key test-not)
1176                (%assoc-test-not item alist test-not)))
1177           (t
1178            (if key
1179                (%assoc-key item alist key)
1180                (%assoc item alist))))))
1181
1182 (defun assoc-if (predicate alist &key key)
1183   #!+sb-doc
1184   "Return the first cons in ALIST whose CAR satisfies PREDICATE. If
1185    KEY is supplied, apply it to the CAR of each cons before testing."
1186   (let ((predicate (%coerce-callable-to-fun predicate))
1187         (key (and key (%coerce-callable-to-fun key))))
1188     (if key
1189         (%assoc-if-key predicate alist key)
1190         (%assoc-if predicate alist))))
1191
1192 (defun assoc-if-not (predicate alist &key key)
1193   #!+sb-doc
1194   "Return the first cons in ALIST whose CAR does not satisfy PREDICATE.
1195   If KEY is supplied, apply it to the CAR of each cons before testing."
1196   (let ((predicate (%coerce-callable-to-fun predicate))
1197         (key (and key (%coerce-callable-to-fun key))))
1198     (if key
1199         (%assoc-if-not-key predicate alist key)
1200         (%assoc-if-not predicate alist))))
1201
1202 (defun rassoc (item alist &key key (test nil testp) (test-not nil notp))
1203   (declare (list alist))
1204   #!+sb-doc
1205   "Return the cons in ALIST whose CDR is equal (by a given test or EQL) to
1206    the ITEM."
1207   (when (and testp notp)
1208     (error ":TEST and :TEST-NOT were both supplied."))
1209   (let ((key (and key (%coerce-callable-to-fun key)))
1210         (test (and testp (%coerce-callable-to-fun test)))
1211         (test-not (and notp (%coerce-callable-to-fun test-not))))
1212     (cond (test
1213            (if key
1214                (%rassoc-key-test item alist key test)
1215                (%rassoc-test item alist test)))
1216           (test-not
1217            (if key
1218                (%rassoc-key-test-not item alist key test-not)
1219                (%rassoc-test-not item alist test-not)))
1220           (t
1221            (if key
1222                (%rassoc-key item alist key)
1223                (%rassoc item alist))))))
1224
1225 (defun rassoc-if (predicate alist &key key)
1226   #!+sb-doc
1227   "Return the first cons in ALIST whose CDR satisfies PREDICATE. If KEY
1228   is supplied, apply it to the CDR of each cons before testing."
1229   (let ((predicate (%coerce-callable-to-fun predicate))
1230         (key (and key (%coerce-callable-to-fun key))))
1231     (if key
1232         (%rassoc-if-key predicate alist key)
1233         (%rassoc-if predicate alist))))
1234
1235 (defun rassoc-if-not (predicate alist &key key)
1236   #!+sb-doc
1237   "Return the first cons in ALIST whose CDR does not satisfy PREDICATE.
1238   If KEY is supplied, apply it to the CDR of each cons before testing."
1239   (let ((predicate (%coerce-callable-to-fun predicate))
1240         (key (and key (%coerce-callable-to-fun key))))
1241     (if key
1242         (%rassoc-if-not-key predicate alist key)
1243         (%rassoc-if-not predicate alist))))
1244 \f
1245 ;;;; mapping functions
1246
1247 ;;; a helper function for implementation of MAPC, MAPCAR, MAPCAN,
1248 ;;; MAPL, MAPLIST, and MAPCON
1249 ;;;
1250 ;;; Map the designated function over the arglists in the appropriate
1251 ;;; way. It is done when any of the arglists runs out. Until then, it
1252 ;;; CDRs down the arglists calling the function and accumulating
1253 ;;; results as desired.
1254 (defun map1 (fun-designator original-arglists accumulate take-car)
1255   (let ((fun (%coerce-callable-to-fun fun-designator)))
1256     (let* ((arglists (copy-list original-arglists))
1257            (ret-list (list nil))
1258            (temp ret-list))
1259       (do ((res nil)
1260            (args '() '()))
1261           ((dolist (x arglists nil) (if (null x) (return t)))
1262            (if accumulate
1263                (cdr ret-list)
1264                (car original-arglists)))
1265         (do ((l arglists (cdr l)))
1266             ((null l))
1267           (push (if take-car (caar l) (car l)) args)
1268           (setf (car l) (cdar l)))
1269         (setq res (apply fun (nreverse args)))
1270         (case accumulate
1271           (:nconc (setq temp (last (nconc temp res))))
1272           (:list (rplacd temp (list res))
1273                  (setq temp (cdr temp))))))))
1274
1275 (defun mapc (function list &rest more-lists)
1276   #!+sb-doc
1277   "Apply FUNCTION to successive elements of lists. Return the second argument."
1278   (map1 function (cons list more-lists) nil t))
1279
1280 (defun mapcar (function list &rest more-lists)
1281   #!+sb-doc
1282   "Apply FUNCTION to successive elements of LIST. Return list of FUNCTION
1283    return values."
1284   (map1 function (cons list more-lists) :list t))
1285
1286 (defun mapcan (function list &rest more-lists)
1287   #!+sb-doc
1288   "Apply FUNCTION to successive elements of LIST. Return NCONC of FUNCTION
1289    results."
1290   (map1 function (cons list more-lists) :nconc t))
1291
1292 (defun mapl (function list &rest more-lists)
1293   #!+sb-doc
1294   "Apply FUNCTION to successive CDRs of list. Return NIL."
1295   (map1 function (cons list more-lists) nil nil))
1296
1297 (defun maplist (function list &rest more-lists)
1298   #!+sb-doc
1299   "Apply FUNCTION to successive CDRs of list. Return list of results."
1300   (map1 function (cons list more-lists) :list nil))
1301
1302 (defun mapcon (function list &rest more-lists)
1303   #!+sb-doc
1304   "Apply FUNCTION to successive CDRs of lists. Return NCONC of results."
1305   (map1 function (cons list more-lists) :nconc nil))
1306
1307 ;;;; Specialized versions
1308
1309 ;;; %ADJOIN-*, %ASSOC-*, %MEMBER-*, and %RASSOC-* functions. Deftransforms
1310 ;;; delegate to TRANSFORM-LIST-PRED-SEEK and TRANSFORM-LIST-ITEM-SEEK which
1311 ;;; pick the appropriate versions. These win because they have only positional
1312 ;;; arguments, the TEST, TEST-NOT & KEY functions are known to exist (or not),
1313 ;;; and are known to be functions instead of function designators. We are also
1314 ;;; able to transform many common cases to -EQ versions, which are
1315 ;;; substantially faster then EQL using ones.
1316 (macrolet
1317     ((def (funs form &optional variant)
1318        (flet ((%def (name &optional conditional)
1319                 (let* ((body-loop
1320                         `(do ((list list (cdr list)))
1321                              ((null list) nil)
1322                            (declare (list list))
1323                            (let ((this (car list)))
1324                              ,(let ((cxx (if (char= #\A (char (string name) 0))
1325                                              'car    ; assoc, assoc-if, assoc-if-not
1326                                              'cdr))) ; rassoc, rassoc-if, rassoc-if-not
1327                                    (ecase name
1328                                       ((assoc rassoc)
1329                                        (if funs
1330                                            `(when this
1331                                               (let ((target (,cxx this)))
1332                                                 (when ,form
1333                                                   (return this))))
1334                                            ;; If there is no TEST/TEST-NOT or
1335                                            ;; KEY, do the EQ/EQL test first,
1336                                            ;; before checking for NIL.
1337                                            `(let ((target (,cxx this)))
1338                                               (when (and ,form this)
1339                                                 (return this)))))
1340                                  ((assoc-if assoc-if-not rassoc-if rassoc-if-not)
1341                                   (aver (equal '(eql x) (subseq form 0 2)))
1342                                   `(when this
1343                                      (let ((target (,cxx this)))
1344                                        (,conditional (funcall ,@(cdr form))
1345                                                      (return this)))))
1346                                  (member
1347                                   `(let ((target this))
1348                                      (when ,form
1349                                        (return list))))
1350                                  ((member-if member-if-not)
1351                                   (aver (equal '(eql x) (subseq form 0 2)))
1352                                   `(let ((target this))
1353                                      (,conditional (funcall ,@(cdr form))
1354                                                    (return list))))
1355                                  (adjoin
1356                                   `(let ((target this))
1357                                      (when ,form
1358                                        (return t)))))))))
1359                        (body (if (eq 'adjoin name)
1360                                  `(if (let ,(when (member 'key funs)
1361                                                   `((x (funcall key x))))
1362                                         ,body-loop)
1363                                       list
1364                                       (cons x list))
1365                                  body-loop)))
1366                   `(defun ,(intern (format nil "%~A~{-~A~}~@[-~A~]" name funs variant))
1367                        (x list ,@funs)
1368                      (declare (optimize speed (sb!c::verify-arg-count 0)))
1369                      ,@(when funs `((declare (function ,@funs))))
1370                      ,@(unless (member name '(member assoc adjoin rassoc)) `((declare (function x))))
1371                      ,body))))
1372          `(progn
1373             ,(%def 'adjoin)
1374             ,(%def 'assoc)
1375             ,(%def 'member)
1376             ,(%def 'rassoc)
1377             ,@(when (and (not variant) (member funs '(() (key)) :test #'equal))
1378                     (list (%def 'member-if 'when)
1379                           (%def 'member-if-not 'unless)
1380                           (%def 'assoc-if 'when)
1381                           (%def 'assoc-if-not 'unless)
1382                           (%def 'rassoc-if 'when)
1383                           (%def 'rassoc-if-not 'unless)))))))
1384   (def ()
1385       (eql x target))
1386   (def ()
1387       (eq x target)
1388     eq)
1389   (def (key)
1390       (eql x (funcall key target)))
1391   (def (key)
1392       (eq x (funcall key target))
1393     eq)
1394   (def (key test)
1395       (funcall test x (funcall key target)))
1396   (def (key test-not)
1397       (not (funcall test-not x (funcall key target))))
1398   (def (test)
1399       (funcall test x target))
1400   (def (test-not)
1401       (not (funcall test-not x target))))