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