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