[N]BUTLAST perform a single pass over the list
[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 (defun butlast (list &optional (n 1))
526   (cond ((zerop n)
527          (copy-list list))
528         ((not (typep n 'index))
529          nil)
530         (t
531          (let ((head (nthcdr (1- n) list)))
532            (and (consp head)      ; there are at least n
533                 (collect ((copy)) ; conses; copy!
534                   (do ((trail list (cdr trail))
535                        (head head (cdr head)))
536                       ;; HEAD is n-1 conses ahead of TRAIL;
537                       ;; when HEAD is at the last cons, return
538                       ;; the data copied so far.
539                       ((atom (cdr head))
540                        (copy))
541                     (copy (car trail)))))))))
542
543 (defun nbutlast (list &optional (n 1))
544   (cond ((zerop n)
545          list)
546         ((not (typep n 'index))
547          nil)
548         (t
549          (let ((head (nthcdr (1- n) list)))
550            (and (consp head)       ; there are more than n
551                 (consp (cdr head)) ; conses.
552                 ;; TRAIL trails by n cons to be able to
553                 ;; cut the list at the cons just before.
554                 (do ((trail list (cdr trail))
555                      (head (cdr head) (cdr head)))
556                     ((atom (cdr head))
557                      (setf (cdr trail) nil)
558                      list)))))))
559
560 (defun ldiff (list object)
561   "Return a new list, whose elements are those of LIST that appear before
562    OBJECT. If OBJECT is not a tail of LIST, a copy of LIST is returned.
563    LIST must be a proper list or a dotted list."
564   (do* ((list list (cdr list))
565         (result (list ()))
566         (splice result))
567        ((atom list)
568         (if (eql list object)
569             (cdr result)
570             (progn (rplacd splice list) (cdr result))))
571     (if (eql list object)
572         (return (cdr result))
573         (setq splice (cdr (rplacd splice (list (car list))))))))
574 \f
575 ;;;; functions to alter list structure
576
577 (defun rplaca (cons x)
578   #!+sb-doc
579   "Change the CAR of CONS to X and return the CONS."
580   (rplaca cons x))
581
582 (defun rplacd (cons x)
583   #!+sb-doc
584   "Change the CDR of CONS to X and return the CONS."
585   (rplacd cons x))
586
587 ;;; The following are for use by SETF.
588
589 (defun %rplaca (x val) (rplaca x val) val)
590
591 (defun %rplacd (x val) (rplacd x val) val)
592
593 ;;; Set the Nth element of LIST to NEWVAL.
594 (defun %setnth (n list newval)
595   (typecase n
596     (index
597      (do ((count n (1- count))
598           (list list (cdr list)))
599          ((endp list)
600           (error "~S is too large an index for SETF of NTH." n))
601        (declare (type fixnum count))
602        (when (<= count 0)
603          (rplaca list newval)
604          (return newval))))
605     (t (let ((cons (nthcdr n list)))
606          (when (endp cons)
607            (error "~S is too large an index for SETF of NTH." n))
608          (rplaca cons newval)
609          newval))))
610 \f
611 ;;;; :KEY arg optimization to save funcall of IDENTITY
612
613 ;;; APPLY-KEY saves us a function call sometimes.
614 ;;;    This isn't wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
615 ;;;    because it's used in seq.lisp and sort.lisp.
616 (defmacro apply-key (key element)
617   `(if ,key
618        (funcall ,key ,element)
619        ,element))
620 \f
621 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
622
623 ;;; Use these with the following &KEY args:
624 (defmacro with-set-keys (funcall)
625   `(if notp
626        ,(append funcall '(:key key :test-not test-not))
627        ,(append funcall '(:key key :test test))))
628
629 (defmacro satisfies-the-test (item elt)
630   (let ((key-tmp (gensym)))
631     `(let ((,key-tmp (apply-key key ,elt)))
632       (cond (testp (funcall test ,item ,key-tmp))
633             (notp (not (funcall test-not ,item ,key-tmp)))
634             (t (funcall test ,item ,key-tmp))))))
635 \f
636 ;;;; substitution of expressions
637
638 (defun subst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
639   #!+sb-doc
640   "Substitutes new for subtrees matching old."
641   (when (and testp notp)
642     (error ":TEST and :TEST-NOT were both supplied."))
643   (let ((key (and key (%coerce-callable-to-fun key)))
644         (test (if testp (%coerce-callable-to-fun test) test))
645         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
646     (declare (type function test test-not))
647     (labels ((s (subtree)
648                (cond ((satisfies-the-test old subtree) new)
649                      ((atom subtree) subtree)
650                      (t (let ((car (s (car subtree)))
651                               (cdr (s (cdr subtree))))
652                           (if (and (eq car (car subtree))
653                                    (eq cdr (cdr subtree)))
654                               subtree
655                               (cons car cdr)))))))
656       (s tree))))
657
658 (defun subst-if (new test tree &key key)
659   #!+sb-doc
660   "Substitutes new for subtrees for which test is true."
661   (let ((test (%coerce-callable-to-fun test))
662         (key (and key (%coerce-callable-to-fun key))))
663     (labels ((s (subtree)
664                (cond ((funcall test (apply-key key subtree)) new)
665                      ((atom subtree) subtree)
666                      (t (let ((car (s (car subtree)))
667                               (cdr (s (cdr subtree))))
668                           (if (and (eq car (car subtree))
669                                    (eq cdr (cdr subtree)))
670                               subtree
671                               (cons car cdr)))))))
672       (s tree))))
673
674 (defun subst-if-not (new test tree &key key)
675   #!+sb-doc
676   "Substitutes new for subtrees for which test is false."
677   (let ((test (%coerce-callable-to-fun test))
678         (key (and key (%coerce-callable-to-fun key))))
679     (labels ((s (subtree)
680                (cond ((not (funcall test (apply-key key subtree))) new)
681                      ((atom subtree) subtree)
682                      (t (let ((car (s (car subtree)))
683                               (cdr (s (cdr subtree))))
684                           (if (and (eq car (car subtree))
685                                    (eq cdr (cdr subtree)))
686                               subtree
687                               (cons car cdr)))))))
688       (s tree))))
689
690 (defun nsubst (new old tree &key key (test #'eql testp) (test-not #'eql notp))
691   #!+sb-doc
692   "Substitute NEW for subtrees matching OLD."
693   (when (and testp notp)
694     (error ":TEST and :TEST-NOT were both supplied."))
695   (let ((key (and key (%coerce-callable-to-fun key)))
696         (test (if testp (%coerce-callable-to-fun test) test))
697         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
698     (declare (type function test test-not))
699     (labels ((s (subtree)
700                (cond ((satisfies-the-test old subtree) new)
701                      ((atom subtree) subtree)
702                      (t (do* ((last nil subtree)
703                               (subtree subtree (cdr subtree)))
704                              ((atom subtree)
705                               (if (satisfies-the-test old subtree)
706                                   (setf (cdr last) new)))
707                           (if (satisfies-the-test old subtree)
708                               (return (setf (cdr last) new))
709                               (setf (car subtree) (s (car subtree)))))
710                         subtree))))
711       (s tree))))
712
713 (defun nsubst-if (new test tree &key key)
714   #!+sb-doc
715   "Substitute NEW for subtrees of TREE for which TEST is true."
716   (let ((test (%coerce-callable-to-fun test))
717         (key (and key (%coerce-callable-to-fun key))))
718     (labels ((s (subtree)
719                (cond ((funcall test (apply-key key subtree)) new)
720                      ((atom subtree) subtree)
721                      (t (do* ((last nil subtree)
722                               (subtree subtree (cdr subtree)))
723                              ((atom subtree)
724                               (if (funcall test (apply-key key subtree))
725                                   (setf (cdr last) new)))
726                           (if (funcall test (apply-key key subtree))
727                               (return (setf (cdr last) new))
728                               (setf (car subtree) (s (car subtree)))))
729                         subtree))))
730       (s tree))))
731
732 (defun nsubst-if-not (new test tree &key key)
733   #!+sb-doc
734   "Substitute NEW for subtrees of TREE for which TEST is false."
735   (let ((test (%coerce-callable-to-fun test))
736         (key (and key (%coerce-callable-to-fun key))))
737     (labels ((s (subtree)
738                (cond ((not (funcall test (apply-key key subtree))) new)
739                      ((atom subtree) subtree)
740                      (t (do* ((last nil subtree)
741                               (subtree subtree (cdr subtree)))
742                              ((atom subtree)
743                               (if (not (funcall test (apply-key key subtree)))
744                                   (setf (cdr last) new)))
745                           (if (not (funcall test (apply-key key subtree)))
746                               (return (setf (cdr last) new))
747                               (setf (car subtree) (s (car subtree)))))
748                         subtree))))
749       (s tree))))
750 \f
751 (defun sublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
752   #!+sb-doc
753   "Substitute from ALIST into TREE nondestructively."
754   (when (and testp notp)
755     (error ":TEST and :TEST-NOT were both supplied."))
756   (let ((key (and key (%coerce-callable-to-fun key)))
757         (test (if testp (%coerce-callable-to-fun test) test))
758         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
759     (declare (type function test test-not))
760     (declare (inline assoc))
761     (labels ((s (subtree)
762                (let* ((key-val (apply-key key subtree))
763                       (assoc (if notp
764                                  (assoc key-val alist :test-not test-not)
765                                  (assoc key-val alist :test test))))
766                  (cond (assoc (cdr assoc))
767                        ((atom subtree) subtree)
768                        (t (let ((car (s (car subtree)))
769                                 (cdr (s (cdr subtree))))
770                             (if (and (eq car (car subtree))
771                                      (eq cdr (cdr subtree)))
772                                 subtree
773                                 (cons car cdr))))))))
774       (s tree))))
775
776 ;;; This is in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
777 ;;; because it can be referenced in inline expansions.
778 (defmacro nsublis-macro ()
779   (let ((key-tmp (gensym)))
780     `(let ((,key-tmp (apply-key key subtree)))
781       (if notp
782           (assoc ,key-tmp alist :test-not test-not)
783           (assoc ,key-tmp alist :test test)))))
784
785 (defun nsublis (alist tree &key key (test #'eql testp) (test-not #'eql notp))
786   #!+sb-doc
787   "Substitute from ALIST into TRUE destructively."
788   (when (and testp notp)
789     (error ":TEST and :TEST-NOT were both supplied."))
790   (let ((key (and key (%coerce-callable-to-fun key)))
791         (test (if testp (%coerce-callable-to-fun test) test))
792         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
793     (declare (inline assoc))
794     (let (temp)
795       (labels ((s (subtree)
796                  (cond ((setq temp (nsublis-macro))
797                         (cdr temp))
798                        ((atom subtree) subtree)
799                        (t (do* ((last nil subtree)
800                                 (subtree subtree (cdr subtree)))
801                                ((atom subtree)
802                                 (if (setq temp (nsublis-macro))
803                                     (setf (cdr last) (cdr temp))))
804                             (if (setq temp (nsublis-macro))
805                                 (return (setf (cdr last) (cdr temp)))
806                                 (setf (car subtree) (s (car subtree)))))
807                           subtree))))
808         (s tree)))))
809 \f
810 ;;;; functions for using lists as sets
811
812 (defun member (item list &key key (test nil testp) (test-not nil notp))
813   #!+sb-doc
814   "Return the tail of LIST beginning with first element satisfying EQLity,
815    :TEST, or :TEST-NOT with the given ITEM."
816   (when (and testp notp)
817     (error ":TEST and :TEST-NOT were both supplied."))
818   (let ((key (and key (%coerce-callable-to-fun key)))
819         (test (and testp (%coerce-callable-to-fun test)))
820         (test-not (and notp (%coerce-callable-to-fun test-not))))
821     (cond (test
822            (if key
823                (%member-key-test item list key test)
824                (%member-test item list test)))
825           (test-not
826            (if key
827                (%member-key-test-not item list key test-not)
828                (%member-test-not item list test-not)))
829           (t
830            (if key
831                (%member-key item list key)
832                (%member item list))))))
833
834 (defun member-if (test list &key key)
835   #!+sb-doc
836   "Return tail of LIST beginning with first element satisfying TEST."
837   (let ((test (%coerce-callable-to-fun test))
838         (key (and key (%coerce-callable-to-fun key))))
839     (if key
840         (%member-if-key test list key)
841         (%member-if test list))))
842
843 (defun member-if-not (test list &key key)
844   #!+sb-doc
845   "Return tail of LIST beginning with first element not satisfying TEST."
846   (let ((test (%coerce-callable-to-fun test))
847         (key (and key (%coerce-callable-to-fun key))))
848     (if key
849         (%member-if-not-key test list key)
850         (%member-if-not test list))))
851
852 (defun tailp (object list)
853   #!+sb-doc
854   "Return true if OBJECT is the same as some tail of LIST, otherwise
855    returns false. LIST must be a proper list or a dotted list."
856   (do ((list list (cdr list)))
857       ((atom list) (eql list object))
858     (if (eql object list)
859         (return t))))
860
861 (defun adjoin (item list &key key (test #'eql testp) (test-not nil notp))
862   #!+sb-doc
863   "Add ITEM to LIST unless it is already a member"
864   (when (and testp notp)
865     (error ":TEST and :TEST-NOT were both supplied."))
866   (let ((key (and key (%coerce-callable-to-fun key)))
867         (test (and testp (%coerce-callable-to-fun test)))
868         (test-not (and notp (%coerce-callable-to-fun test-not))))
869     (cond (test
870            (if key
871                (%adjoin-key-test item list key test)
872                (%adjoin-test item list test)))
873           (test-not
874            (if key
875                (%adjoin-key-test-not item list key test-not)
876                (%adjoin-test-not item list test-not)))
877           (t
878            (if key
879                (%adjoin-key item list key)
880                (%adjoin item list))))))
881
882 (defconstant +list-based-union-limit+ 80)
883
884 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
885   #!+sb-doc
886   "Return the union of LIST1 and LIST2."
887   (declare (inline member))
888   (when (and testp notp)
889     (error ":TEST and :TEST-NOT were both supplied."))
890   ;; We have two possibilities here: for shortish lists we pick up the
891   ;; shorter one as the result, and add the other one to it. For long
892   ;; lists we use a hash-table when possible.
893   (let ((n1 (length list1))
894         (n2 (length list2))
895         (key (and key (%coerce-callable-to-fun key)))
896         (test (if notp
897                   (let ((test-not-fun (%coerce-callable-to-fun test-not)))
898                     (lambda (x y) (not (funcall test-not-fun x y))))
899                   (%coerce-callable-to-fun test))))
900     (multiple-value-bind (short long n-short)
901         (if (< n1 n2)
902             (values list1 list2 n1)
903             (values list2 list1 n2))
904       (if (or (< n-short +list-based-union-limit+)
905               (not (member test (list #'eq #'eql #'equal #'equalp))))
906           (let ((orig short))
907             (dolist (elt long)
908               (unless (member (apply-key key elt) orig :key key :test test)
909                 (push elt short)))
910             short)
911           (let ((table (make-hash-table :test test :size (+ n1 n2)))
912                 (union nil))
913             (dolist (elt long)
914               (setf (gethash (apply-key key elt) table) elt))
915             (dolist (elt short)
916               (setf (gethash (apply-key key elt) table) elt))
917             (maphash (lambda (k v)
918                        (declare (ignore k))
919                        (push v union))
920                      table)
921             union)))))
922
923 ;;; Destination and source are SETF-able and many-evaluable. Set the
924 ;;; SOURCE to the CDR, and "cons" the 1st elt of source to DESTINATION.
925 ;;;
926 ;;; FIXME: needs a more mnemonic name
927 (defmacro steve-splice (source destination)
928   `(let ((temp ,source))
929      (setf ,source (cdr ,source)
930            (cdr temp) ,destination
931            ,destination temp)))
932
933 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
934   #!+sb-doc
935   "Destructively return the union of LIST1 and LIST2."
936   (declare (inline member))
937   (when (and testp notp)
938     (error ":TEST and :TEST-NOT were both supplied."))
939   ;; We have two possibilities here: for shortish lists we pick up the
940   ;; shorter one as the result, and add the other one to it. For long
941   ;; lists we use a hash-table when possible.
942   (let ((n1 (length list1))
943         (n2 (length list2))
944         (key (and key (%coerce-callable-to-fun key)))
945         (test (if notp
946                   (let ((test-not-fun (%coerce-callable-to-fun test-not)))
947                     (lambda (x y) (not (funcall test-not-fun x y))))
948                   (%coerce-callable-to-fun test))))
949     (multiple-value-bind (short long n-short)
950         (if (< n1 n2)
951             (values list1 list2 n1)
952             (values list2 list1 n2))
953       (if (or (< n-short +list-based-union-limit+)
954               (not (member test (list #'eq #'eql #'equal #'equalp))))
955           (let ((orig short))
956             (do ((elt (car long) (car long)))
957                 ((endp long))
958               (if (not (member (apply-key key elt) orig :key key :test test))
959                   (steve-splice long short)
960                   (setf long (cdr long))))
961             short)
962           (let ((table (make-hash-table :test test :size (+ n1 n2))))
963             (dolist (elt long)
964               (setf (gethash (apply-key key elt) table) elt))
965             (dolist (elt short)
966               (setf (gethash (apply-key key elt) table) elt))
967             (let ((union long)
968                   (head long))
969               (maphash (lambda (k v)
970                          (declare (ignore k))
971                          (if head
972                              (setf (car head) v
973                                    head (cdr head))
974                              (push v union)))
975                       table)
976               union))))))
977
978 (defun intersection (list1 list2
979                      &key key (test #'eql testp) (test-not nil notp))
980   #!+sb-doc
981   "Return the intersection of LIST1 and LIST2."
982   (declare (inline member))
983   (when (and testp notp)
984     (error ":TEST and :TEST-NOT were both supplied."))
985   (let ((key (and key (%coerce-callable-to-fun key))))
986     (let ((res nil))
987       (dolist (elt list1)
988         (if (with-set-keys (member (apply-key key elt) list2))
989             (push elt res)))
990       res)))
991
992 (defun nintersection (list1 list2
993                       &key key (test #'eql testp) (test-not nil notp))
994   #!+sb-doc
995   "Destructively return the intersection of LIST1 and LIST2."
996   (declare (inline member))
997   (when (and testp notp)
998     (error ":TEST and :TEST-NOT were both supplied."))
999   (let ((key (and key (%coerce-callable-to-fun key))))
1000     (let ((res nil)
1001           (list1 list1))
1002       (do () ((endp list1))
1003         (if (with-set-keys (member (apply-key key (car list1)) list2))
1004             (steve-splice list1 res)
1005             (setq list1 (cdr list1))))
1006       res)))
1007
1008 (defun set-difference (list1 list2
1009                        &key key (test #'eql testp) (test-not nil notp))
1010   #!+sb-doc
1011   "Return the elements of LIST1 which are not in LIST2."
1012   (declare (inline member))
1013   (when (and testp notp)
1014     (error ":TEST and :TEST-NOT were both supplied."))
1015   (let ((key (and key (%coerce-callable-to-fun key))))
1016     (if (null list2)
1017         list1
1018         (let ((res nil))
1019           (dolist (elt list1)
1020             (if (not (with-set-keys (member (apply-key key elt) list2)))
1021                 (push elt res)))
1022           res))))
1023
1024 (defun nset-difference (list1 list2
1025                         &key key (test #'eql testp) (test-not nil notp))
1026   #!+sb-doc
1027   "Destructively return the elements of LIST1 which are not in LIST2."
1028   (declare (inline member))
1029   (when (and testp notp)
1030     (error ":TEST and :TEST-NOT were both supplied."))
1031   (let ((key (and key (%coerce-callable-to-fun key))))
1032     (let ((res nil)
1033           (list1 list1))
1034       (do () ((endp list1))
1035         (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
1036             (steve-splice list1 res)
1037             (setq list1 (cdr list1))))
1038       res)))
1039
1040 (defun set-exclusive-or (list1 list2
1041                          &key key (test #'eql testp) (test-not #'eql notp))
1042   #!+sb-doc
1043   "Return new list of elements appearing exactly once in LIST1 and LIST2."
1044   (declare (inline member))
1045   (when (and testp notp)
1046     (error ":TEST and :TEST-NOT were both supplied."))
1047   (let ((result nil)
1048         (key (and key (%coerce-callable-to-fun key)))
1049         (test (if testp (%coerce-callable-to-fun test) test))
1050         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
1051     (declare (type function test test-not))
1052     (dolist (elt list1)
1053       (unless (with-set-keys (member (apply-key key elt) list2))
1054         (setq result (cons elt result))))
1055     (let ((test (if testp
1056                     (lambda (x y) (funcall test y x))
1057                     test))
1058           (test-not (if notp
1059                         (lambda (x y) (funcall test-not y x))
1060                         test-not)))
1061       (dolist (elt list2)
1062         (unless (with-set-keys (member (apply-key key elt) list1))
1063           (setq result (cons elt result)))))
1064     result))
1065
1066 (defun nset-exclusive-or (list1 list2
1067                           &key key (test #'eql testp) (test-not #'eql notp))
1068   #!+sb-doc
1069   "Destructively return a list with elements which appear but once in LIST1
1070    and LIST2."
1071   (when (and testp notp)
1072     (error ":TEST and :TEST-NOT were both supplied."))
1073   (let ((key (and key (%coerce-callable-to-fun key)))
1074         (test (if testp (%coerce-callable-to-fun test) test))
1075         (test-not (if notp (%coerce-callable-to-fun test-not) test-not)))
1076     (declare (type function test test-not))
1077     ;; The outer loop examines LIST1 while the inner loop examines
1078     ;; LIST2. If an element is found in LIST2 "equal" to the element
1079     ;; in LIST1, both are spliced out. When the end of LIST1 is
1080     ;; reached, what is left of LIST2 is tacked onto what is left of
1081     ;; LIST1. The splicing operation ensures that the correct
1082     ;; operation is performed depending on whether splice is at the
1083     ;; top of the list or not.
1084     (do ((list1 list1)
1085          (list2 list2)
1086          (x list1 (cdr x))
1087          (splicex ())
1088          (deleted-y ())
1089          ;; elements of LIST2, which are "equal" to some processed
1090          ;; earlier elements of LIST1
1091          )
1092         ((endp x)
1093          (if (null splicex)
1094              (setq list1 list2)
1095              (rplacd splicex list2))
1096          list1)
1097       (let ((key-val-x (apply-key key (car x)))
1098             (found-duplicate nil))
1099
1100         ;; Move all elements from LIST2, which are "equal" to (CAR X),
1101         ;; to DELETED-Y.
1102         (do* ((y list2 next-y)
1103               (next-y (cdr y) (cdr y))
1104               (splicey ()))
1105              ((endp y))
1106           (cond ((let ((key-val-y (apply-key key (car y))))
1107                    (if notp
1108                        (not (funcall test-not key-val-x key-val-y))
1109                        (funcall test key-val-x key-val-y)))
1110                  (if (null splicey)
1111                      (setq list2 (cdr y))
1112                      (rplacd splicey (cdr y)))
1113                  (setq deleted-y (rplacd y deleted-y))
1114                  (setq found-duplicate t))
1115                 (t (setq splicey y))))
1116
1117         (unless found-duplicate
1118           (setq found-duplicate (with-set-keys (member key-val-x deleted-y))))
1119
1120         (if found-duplicate
1121             (if (null splicex)
1122                 (setq list1 (cdr x))
1123                 (rplacd splicex (cdr x)))
1124             (setq splicex x))))))
1125
1126 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
1127   #!+sb-doc
1128   "Return T if every element in LIST1 is also in LIST2."
1129   (declare (inline member))
1130   (when (and testp notp)
1131     (error ":TEST and :TEST-NOT were both supplied."))
1132   (let ((key (and key (%coerce-callable-to-fun key))))
1133     (dolist (elt list1)
1134       (unless (with-set-keys (member (apply-key key elt) list2))
1135         (return-from subsetp nil)))
1136     t))
1137 \f
1138 ;;;; functions that operate on association lists
1139
1140 (defun acons (key datum alist)
1141   #!+sb-doc
1142   "Construct a new alist by adding the pair (KEY . DATUM) to ALIST."
1143   (cons (cons key datum) alist))
1144
1145 (defun pairlis (keys data &optional (alist '()))
1146   #!+sb-doc
1147   "Construct an association list from KEYS and DATA (adding to ALIST)."
1148   (do ((x keys (cdr x))
1149        (y data (cdr y)))
1150       ((and (endp x) (endp y)) alist)
1151     (if (or (endp x) (endp y))
1152         (error "The lists of keys and data are of unequal length."))
1153     (setq alist (acons (car x) (car y) alist))))
1154
1155 (defun assoc (item alist &key key (test nil testp) (test-not nil notp))
1156   #!+sb-doc
1157   "Return the cons in ALIST whose car is equal (by a given test or EQL) to
1158    the ITEM."
1159   (when (and testp notp)
1160     (error ":TEST and :TEST-NOT were both supplied."))
1161   (let ((key (and key (%coerce-callable-to-fun key)))
1162         (test (and testp (%coerce-callable-to-fun test)))
1163         (test-not (and notp (%coerce-callable-to-fun test-not))))
1164     (cond (test
1165            (if key
1166                (%assoc-key-test item alist key test)
1167                (%assoc-test item alist test)))
1168           (test-not
1169            (if key
1170                (%assoc-key-test-not item alist key test-not)
1171                (%assoc-test-not item alist test-not)))
1172           (t
1173            (if key
1174                (%assoc-key item alist key)
1175                (%assoc item alist))))))
1176
1177 (defun assoc-if (predicate alist &key key)
1178   #!+sb-doc
1179   "Return the first cons in ALIST whose CAR satisfies PREDICATE. If
1180    KEY is supplied, apply it to the CAR of each cons before testing."
1181   (let ((predicate (%coerce-callable-to-fun predicate))
1182         (key (and key (%coerce-callable-to-fun key))))
1183     (if key
1184         (%assoc-if-key predicate alist key)
1185         (%assoc-if predicate alist))))
1186
1187 (defun assoc-if-not (predicate alist &key key)
1188   #!+sb-doc
1189   "Return the first cons in ALIST whose CAR does not satisfy PREDICATE.
1190   If KEY is supplied, apply it to the CAR of each cons before testing."
1191   (let ((predicate (%coerce-callable-to-fun predicate))
1192         (key (and key (%coerce-callable-to-fun key))))
1193     (if key
1194         (%assoc-if-not-key predicate alist key)
1195         (%assoc-if-not predicate alist))))
1196
1197 (defun rassoc (item alist &key key (test nil testp) (test-not nil notp))
1198   (declare (list alist))
1199   #!+sb-doc
1200   "Return the cons in ALIST whose CDR is equal (by a given test or EQL) to
1201    the ITEM."
1202   (when (and testp notp)
1203     (error ":TEST and :TEST-NOT were both supplied."))
1204   (let ((key (and key (%coerce-callable-to-fun key)))
1205         (test (and testp (%coerce-callable-to-fun test)))
1206         (test-not (and notp (%coerce-callable-to-fun test-not))))
1207     (cond (test
1208            (if key
1209                (%rassoc-key-test item alist key test)
1210                (%rassoc-test item alist test)))
1211           (test-not
1212            (if key
1213                (%rassoc-key-test-not item alist key test-not)
1214                (%rassoc-test-not item alist test-not)))
1215           (t
1216            (if key
1217                (%rassoc-key item alist key)
1218                (%rassoc item alist))))))
1219
1220 (defun rassoc-if (predicate alist &key key)
1221   #!+sb-doc
1222   "Return the first cons in ALIST whose CDR satisfies PREDICATE. If KEY
1223   is supplied, apply it to the CDR of each cons before testing."
1224   (let ((predicate (%coerce-callable-to-fun predicate))
1225         (key (and key (%coerce-callable-to-fun key))))
1226     (if key
1227         (%rassoc-if-key predicate alist key)
1228         (%rassoc-if predicate alist))))
1229
1230 (defun rassoc-if-not (predicate alist &key key)
1231   #!+sb-doc
1232   "Return the first cons in ALIST whose CDR does not satisfy PREDICATE.
1233   If KEY is supplied, apply it to the CDR of each cons before testing."
1234   (let ((predicate (%coerce-callable-to-fun predicate))
1235         (key (and key (%coerce-callable-to-fun key))))
1236     (if key
1237         (%rassoc-if-not-key predicate alist key)
1238         (%rassoc-if-not predicate alist))))
1239 \f
1240 ;;;; mapping functions
1241
1242 ;;; a helper function for implementation of MAPC, MAPCAR, MAPCAN,
1243 ;;; MAPL, MAPLIST, and MAPCON
1244 ;;;
1245 ;;; Map the designated function over the arglists in the appropriate
1246 ;;; way. It is done when any of the arglists runs out. Until then, it
1247 ;;; CDRs down the arglists calling the function and accumulating
1248 ;;; results as desired.
1249 (defun map1 (fun-designator original-arglists accumulate take-car)
1250   (let ((fun (%coerce-callable-to-fun fun-designator)))
1251     (let* ((arglists (copy-list original-arglists))
1252            (ret-list (list nil))
1253            (temp ret-list))
1254       (do ((res nil)
1255            (args '() '()))
1256           ((dolist (x arglists nil) (if (null x) (return t)))
1257            (if accumulate
1258                (cdr ret-list)
1259                (car original-arglists)))
1260         (do ((l arglists (cdr l)))
1261             ((null l))
1262           (push (if take-car (caar l) (car l)) args)
1263           (setf (car l) (cdar l)))
1264         (setq res (apply fun (nreverse args)))
1265         (case accumulate
1266           (:nconc (setq temp (last (nconc temp res))))
1267           (:list (rplacd temp (list res))
1268                  (setq temp (cdr temp))))))))
1269
1270 (defun mapc (function list &rest more-lists)
1271   #!+sb-doc
1272   "Apply FUNCTION to successive elements of lists. Return the second argument."
1273   (map1 function (cons list more-lists) nil t))
1274
1275 (defun mapcar (function list &rest more-lists)
1276   #!+sb-doc
1277   "Apply FUNCTION to successive elements of LIST. Return list of FUNCTION
1278    return values."
1279   (map1 function (cons list more-lists) :list t))
1280
1281 (defun mapcan (function list &rest more-lists)
1282   #!+sb-doc
1283   "Apply FUNCTION to successive elements of LIST. Return NCONC of FUNCTION
1284    results."
1285   (map1 function (cons list more-lists) :nconc t))
1286
1287 (defun mapl (function list &rest more-lists)
1288   #!+sb-doc
1289   "Apply FUNCTION to successive CDRs of list. Return NIL."
1290   (map1 function (cons list more-lists) nil nil))
1291
1292 (defun maplist (function list &rest more-lists)
1293   #!+sb-doc
1294   "Apply FUNCTION to successive CDRs of list. Return list of results."
1295   (map1 function (cons list more-lists) :list nil))
1296
1297 (defun mapcon (function list &rest more-lists)
1298   #!+sb-doc
1299   "Apply FUNCTION to successive CDRs of lists. Return NCONC of results."
1300   (map1 function (cons list more-lists) :nconc nil))
1301
1302 ;;;; Specialized versions
1303
1304 ;;; %ADJOIN-*, %ASSOC-*, %MEMBER-*, and %RASSOC-* functions. Deftransforms
1305 ;;; delegate to TRANSFORM-LIST-PRED-SEEK and TRANSFORM-LIST-ITEM-SEEK which
1306 ;;; pick the appropriate versions. These win because they have only positional
1307 ;;; arguments, the TEST, TEST-NOT & KEY functions are known to exist (or not),
1308 ;;; and are known to be functions instead of function designators. We are also
1309 ;;; able to transform many common cases to -EQ versions, which are
1310 ;;; substantially faster then EQL using ones.
1311 (macrolet
1312     ((def (funs form &optional variant)
1313        (flet ((%def (name &optional conditional)
1314                 (let* ((body-loop
1315                         `(do ((list list (cdr list)))
1316                              ((null list) nil)
1317                            (declare (list list))
1318                            (let ((this (car list)))
1319                              ,(let ((cxx (if (char= #\A (char (string name) 0))
1320                                              'car    ; assoc, assoc-if, assoc-if-not
1321                                              'cdr))) ; rassoc, rassoc-if, rassoc-if-not
1322                                    (ecase name
1323                                       ((assoc rassoc)
1324                                        (if funs
1325                                            `(when this
1326                                               (let ((target (,cxx this)))
1327                                                 (when ,form
1328                                                   (return this))))
1329                                            ;; If there is no TEST/TEST-NOT or
1330                                            ;; KEY, do the EQ/EQL test first,
1331                                            ;; before checking for NIL.
1332                                            `(let ((target (,cxx this)))
1333                                               (when (and ,form this)
1334                                                 (return this)))))
1335                                  ((assoc-if assoc-if-not rassoc-if rassoc-if-not)
1336                                   (aver (equal '(eql x) (subseq form 0 2)))
1337                                   `(when this
1338                                      (let ((target (,cxx this)))
1339                                        (,conditional (funcall ,@(cdr form))
1340                                                      (return this)))))
1341                                  (member
1342                                   `(let ((target this))
1343                                      (when ,form
1344                                        (return list))))
1345                                  ((member-if member-if-not)
1346                                   (aver (equal '(eql x) (subseq form 0 2)))
1347                                   `(let ((target this))
1348                                      (,conditional (funcall ,@(cdr form))
1349                                                    (return list))))
1350                                  (adjoin
1351                                   `(let ((target this))
1352                                      (when ,form
1353                                        (return t)))))))))
1354                        (body (if (eq 'adjoin name)
1355                                  `(if (let ,(when (member 'key funs)
1356                                                   `((x (funcall key x))))
1357                                         ,body-loop)
1358                                       list
1359                                       (cons x list))
1360                                  body-loop)))
1361                   `(defun ,(intern (format nil "%~A~{-~A~}~@[-~A~]" name funs variant))
1362                        (x list ,@funs)
1363                      (declare (optimize speed (sb!c::verify-arg-count 0)))
1364                      ,@(when funs `((declare (function ,@funs))))
1365                      ,@(unless (member name '(member assoc adjoin rassoc)) `((declare (function x))))
1366                      ,body))))
1367          `(progn
1368             ,(%def 'adjoin)
1369             ,(%def 'assoc)
1370             ,(%def 'member)
1371             ,(%def 'rassoc)
1372             ,@(when (and (not variant) (member funs '(() (key)) :test #'equal))
1373                     (list (%def 'member-if 'when)
1374                           (%def 'member-if-not 'unless)
1375                           (%def 'assoc-if 'when)
1376                           (%def 'assoc-if-not 'unless)
1377                           (%def 'rassoc-if 'when)
1378                           (%def 'rassoc-if-not 'unless)))))))
1379   (def ()
1380       (eql x target))
1381   (def ()
1382       (eq x target)
1383     eq)
1384   (def (key)
1385       (eql x (funcall key target)))
1386   (def (key)
1387       (eq x (funcall key target))
1388     eq)
1389   (def (key test)
1390       (funcall test x (funcall key target)))
1391   (def (key test-not)
1392       (not (funcall test-not x (funcall key target))))
1393   (def (test)
1394       (funcall test x target))
1395   (def (test-not)
1396       (not (funcall test-not x target))))