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