0.pre7.46:
[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   (cond ((consp x)
117          (and (consp y)
118               (tree-equal-test-not (car x) (car y) test-not)
119               (tree-equal-test-not (cdr x) (cdr y) test-not)))
120         ((consp y) nil)
121         ((not (funcall test-not x y)) t)
122         (t ())))
123
124 (defun tree-equal-test (x y test)
125   (cond ((consp x)
126          (and (consp y)
127               (tree-equal-test (car x) (car y) test)
128               (tree-equal-test (cdr x) (cdr y) test)))
129         ((consp y) nil)
130         ((funcall test x y) t)
131         (t ())))
132
133 (defun tree-equal (x y &key (test #'eql) test-not)
134   #!+sb-doc
135   "Returns T if X and Y are isomorphic trees with identical leaves."
136   (if test-not
137       (tree-equal-test-not x y test-not)
138       (tree-equal-test x y test)))
139
140 (defun endp (object)
141   #!+sb-doc
142   "The recommended way to test for the end of a list. True if Object is nil,
143    false if Object is a cons, and an error for any other types of arguments."
144   (endp object))
145
146 (defun list-length (list)
147   #!+sb-doc
148   "Returns the length of the given List, or Nil if the List is circular."
149   (do ((n 0 (+ n 2))
150        (y list (cddr y))
151        (z list (cdr z)))
152       (())
153     (declare (fixnum n) (list y z))
154     (when (endp y) (return n))
155     (when (endp (cdr y)) (return (+ n 1)))
156     (when (and (eq y z) (> n 0)) (return nil))))
157
158 (defun nth (n list)
159   #!+sb-doc
160   "Returns the nth object in a list where the car is the zero-th element."
161   (car (nthcdr n list)))
162
163 (defun first (list)
164   #!+sb-doc
165   "Returns the 1st object in a list or NIL if the list is empty."
166   (car list))
167 (defun second (list)
168   "Returns the 2nd object in a list or NIL if there is no 2nd object."
169   (cadr list))
170 (defun third (list)
171   #!+sb-doc
172   "Returns the 3rd object in a list or NIL if there is no 3rd object."
173   (caddr list))
174 (defun fourth (list)
175   #!+sb-doc
176   "Returns the 4th object in a list or NIL if there is no 4th object."
177   (cadddr list))
178 (defun fifth (list)
179   #!+sb-doc
180   "Returns the 5th object in a list or NIL if there is no 5th object."
181   (car (cddddr list)))
182 (defun sixth (list)
183   #!+sb-doc
184   "Returns the 6th object in a list or NIL if there is no 6th object."
185   (cadr (cddddr list)))
186 (defun seventh (list)
187   #!+sb-doc
188   "Returns the 7th object in a list or NIL if there is no 7th object."
189   (caddr (cddddr list)))
190 (defun eighth (list)
191   #!+sb-doc
192   "Returns the 8th object in a list or NIL if there is no 8th object."
193   (cadddr (cddddr list)))
194 (defun ninth (list)
195   #!+sb-doc
196   "Returns the 9th object in a list or NIL if there is no 9th object."
197   (car (cddddr (cddddr list))))
198 (defun tenth (list)
199   #!+sb-doc
200   "Returns the 10th object in a list or NIL if there is no 10th object."
201   (cadr (cddddr (cddddr list))))
202 (defun rest (list)
203   #!+sb-doc
204   "Means the same as the cdr of a list."
205   (cdr list))
206
207 (defun nthcdr (n list)
208   (declare (type index n))
209   #!+sb-doc
210   "Performs the cdr function n times on a list."
211   (do ((i n (1- i))
212        (result list (cdr result)))
213       ((not (plusp i)) result)
214       (declare (type index i))))
215
216 (defun last (list &optional (n 1))
217   #!+sb-doc
218   "Returns the last N conses (not the last element!) of a list."
219   (declare (type index n))
220   (do ((checked-list list (cdr checked-list))
221        (returned-list list)
222        (index 0 (1+ index)))
223       ((atom checked-list) returned-list)
224     (declare (type index index))
225     (if (>= index n)
226         (pop returned-list))))
227
228 (defun list (&rest args)
229   #!+sb-doc
230   "Returns constructs and returns a list of its arguments."
231   args)
232
233 ;;; List* is done the same as list, except that the last cons is made a
234 ;;; dotted pair
235
236 (defun list* (arg &rest others)
237   #!+sb-doc
238   "Returns a list of the arguments with last cons a dotted pair"
239   (cond ((atom others) arg)
240         ((atom (cdr others)) (cons arg (car others)))
241         (t (do ((x others (cdr x)))
242                ((null (cddr x)) (rplacd x (cadr x))))
243            (cons arg others))))
244
245 (defun make-list (size &key initial-element)
246   #!+sb-doc
247   "Constructs a list with size elements each set to value"
248   (declare (type index size))
249   (do ((count size (1- count))
250        (result '() (cons initial-element result)))
251       ((zerop count) result)
252     (declare (type index count))))
253 \f
254 ;;; The outer loop finds the first non-null list and the result is started.
255 ;;; The remaining lists in the arguments are tacked to the end of the result
256 ;;; using splice which cdr's down the end of the new list
257
258 (defun append (&rest lists)
259   #!+sb-doc
260   "Construct a new list by concatenating the list arguments"
261   (do ((top lists (cdr top)))    ;;Cdr to first non-null list.
262       ((atom top) '())
263     (cond ((null (car top)))                            ; Nil -> Keep looping
264           ((not (consp (car top)))                      ; Non cons
265            (if (cdr top)
266                (error "~S is not a list." (car top))
267                (return (car top))))
268           (t                                            ; Start appending
269            (return
270              (if (atom (cdr top))
271                  (car top)    ;;Special case.
272                  (let* ((result (cons (caar top) '()))
273                         (splice result))
274                    (do ((x (cdar top) (cdr x)))  ;;Copy first list
275                        ((atom x))
276                      (setq splice
277                            (cdr (rplacd splice (cons (car x) ()) ))) )
278                    (do ((y (cdr top) (cdr y)))   ;;Copy rest of lists.
279                        ((atom (cdr y))
280                         (setq splice (rplacd splice (car y)))
281                         result)
282                      (if (listp (car y))
283                          (do ((x (car y) (cdr x)))   ;;Inner copy loop.
284                              ((atom x))
285                            (setq
286                             splice
287                             (cdr (rplacd splice (cons (car x) ())))))
288                          (error "~S is not a list." (car y)))))))))))
289 \f
290 ;;; list copying functions
291
292 (defun copy-list (list)
293   #!+sb-doc
294   "Returns a new list which is EQUAL to LIST."
295   ;; The list is copied correctly even if the list is not terminated
296   ;; by NIL. The new list is built by CDR'ing SPLICE which is always
297   ;; at the tail of the new list.
298   (if (atom list)
299       list
300       (let ((result (list (car list))))
301         (do ((x (cdr list) (cdr x))
302              (splice result
303                      (cdr (rplacd splice (cons (car x) '() ))) ))
304             ((atom x)
305              (unless (null x)
306                (rplacd splice x))))
307         result)))
308
309 (defun copy-alist (alist)
310   #!+sb-doc
311   "Returns a new association list which is EQUAL to ALIST."
312   (if (atom alist)
313       alist
314       (let ((result
315              (cons (if (atom (car alist))
316                        (car alist)
317                        (cons (caar alist) (cdar alist)) )
318                    nil)))
319         (do ((x (cdr alist) (cdr x))
320              (splice result
321                      (cdr (rplacd splice
322                                   (cons
323                                    (if (atom (car x))
324                                        (car x)
325                                        (cons (caar x) (cdar x)))
326                                    nil)))))
327             ;; Non-null terminated alist done here.
328             ((atom x)
329              (unless (null x)
330                (rplacd splice x))))
331         result)))
332
333 (defun copy-tree (object)
334   #!+sb-doc
335   "Recursively copy trees of conses."
336   (if (consp object)
337       (cons (copy-tree (car object)) (copy-tree (cdr object)))
338       object))
339 \f
340 ;;; more commonly-used list functions
341
342 (defun revappend (x y)
343   #!+sb-doc
344   "Returns (append (reverse x) y)"
345   (do ((top x (cdr top))
346        (result y (cons (car top) result)))
347       ((endp top) result)))
348
349 ;;; NCONC finds the first non-null list, so it can make splice point
350 ;;; to a cons. After finding the first cons element, it holds it in a
351 ;;; result variable while running down successive elements tacking
352 ;;; them together. While tacking lists together, if we encounter a
353 ;;; null list, we set the previous list's last cdr to nil just in case
354 ;;; it wasn't already nil, and it could have been dotted while the
355 ;;; null list was the last argument to NCONC. The manipulation of
356 ;;; splice (that is starting it out on a first cons, setting LAST of
357 ;;; splice, and setting splice to ele) inherently handles (nconc x x),
358 ;;; and it avoids running down the last argument to NCONC which allows
359 ;;; the last argument to be circular.
360 (defun nconc (&rest lists)
361   #!+sb-doc
362   "Concatenates the lists given as arguments (by changing them)"
363   (do ((top lists (cdr top)))
364       ((null top) nil)
365     (let ((top-of-top (car top)))
366       (typecase top-of-top
367         (cons
368          (let* ((result top-of-top)
369                 (splice result))
370            (do ((elements (cdr top) (cdr elements)))
371                ((endp elements))
372              (let ((ele (car elements)))
373                (typecase ele
374                  (cons (rplacd (last splice) ele)
375                        (setf splice ele))
376                  (null (rplacd (last splice) nil))
377                  (atom (if (cdr elements)
378                            (error "Argument is not a list -- ~S." ele)
379                            (rplacd (last splice) ele)))
380                  (t (error "Argument is not a list -- ~S." ele)))))
381            (return result)))
382         (null)
383         (atom
384          (if (cdr top)
385              (error "Argument is not a list -- ~S." top-of-top)
386              (return top-of-top)))
387         (t (error "Argument is not a list -- ~S." top-of-top))))))
388
389 (defun nreconc (x y)
390   #!+sb-doc
391   "Returns (nconc (nreverse x) y)"
392   (do ((1st (cdr x) (if (atom 1st) 1st (cdr 1st)))
393        (2nd x 1st)              ;2nd follows first down the list.
394        (3rd y 2nd))             ;3rd follows 2nd down the list.
395       ((atom 2nd) 3rd)
396     (rplacd 2nd 3rd)))
397 \f
398 (flet (;; Return the number of conses at the head of the
399        ;; possibly-improper list LIST. (Or if LIST is circular, you
400        ;; lose.)
401        (count-conses (list)
402          (do ((in-list list (cdr in-list))
403               (result 0 (1+ result)))
404              ((atom in-list)
405               result)
406            (declare (type index result)))))
407   (declare (ftype (function (t) index) count-conses))
408   (defun butlast (list &optional (n 1))
409     (let ((n-conses-in-list (count-conses list)))
410       (cond ((zerop n)
411              ;; (We can't use SUBSEQ in this case because LIST isn't
412              ;; necessarily a proper list, but SUBSEQ expects a
413              ;; proper sequence. COPY-LIST isn't so fussy.)
414              (copy-list list))
415             ((>= n n-conses-in-list)
416              nil)
417             (t
418              ;; (LIST isn't necessarily a proper list in this case
419              ;; either, and technically SUBSEQ wants a proper
420              ;; sequence, but no reasonable implementation of SUBSEQ
421              ;; will actually walk down to the end of the list to
422              ;; check, and since we're calling our own implementation
423              ;; we know it's reasonable, so it's OK.)
424              (subseq list 0 (- n-conses-in-list n))))))
425   (defun nbutlast (list &optional (n 1))
426     (if (zerop n)
427         list
428         (let ((n-conses-in-list (count-conses list)))
429           (unless (<= n-conses-in-list n)
430             (setf (cdr (nthcdr (- n-conses-in-list n 1) list))
431                   nil)
432             list)))))
433
434 (defun ldiff (list object)
435   "Return a new list, whose elements are those of LIST that appear before
436    OBJECT. If OBJECT is not a tail of LIST, a copy of LIST is returned.
437    LIST must be a proper list or a dotted list."
438   (do* ((list list (cdr list))
439         (result (list ()))
440         (splice result))
441        ((atom list)
442         (if (eql list object)
443             (cdr result)
444             (progn (rplacd splice list) (cdr result))))
445     (if (eql list object)
446         (return (cdr result))
447         (setq splice (cdr (rplacd splice (list (car list))))))))
448 \f
449 ;;;; functions to alter list structure
450
451 (defun rplaca (x y)
452   #!+sb-doc
453   "Change the CAR of X to Y and return the new X."
454   (rplaca x y))
455
456 (defun rplacd (x y)
457   #!+sb-doc
458   "Change the CDR of X to Y and return the new X."
459   (rplacd x y))
460
461 ;;; The following are for use by SETF.
462
463 (defun %rplaca (x val) (rplaca x val) val)
464
465 (defun %rplacd (x val) (rplacd x val) val)
466
467 ;;; Set the Nth element of LIST to NEWVAL.
468 (defun %setnth (n list newval)
469   (declare (type index n))
470   (do ((count n (1- count))
471        (list list (cdr list)))
472       ((endp list)
473        (error "~S is too large an index for SETF of NTH." n))
474     (declare (fixnum count))
475     (when (<= count 0)
476       (rplaca list newval)
477       (return newval))))
478 \f
479 ;;;; :KEY arg optimization to save funcall of IDENTITY
480
481 ;;; APPLY-KEY saves us a function call sometimes.
482 ;;;    This isn't wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
483 ;;;    because it's used in seq.lisp and sort.lisp.
484 (defmacro apply-key (key element)
485   `(if ,key
486        (funcall ,key ,element)
487        ,element))
488 \f
489 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
490
491 ;;; Use these with the following &KEY args:
492 (defmacro with-set-keys (funcall)
493   `(cond ((and testp notp) (error ":TEST and :TEST-NOT were both supplied."))
494          (notp ,(append funcall '(:key key :test-not test-not)))
495          (t ,(append funcall '(:key key :test test)))))
496
497 (defmacro satisfies-the-test (item elt)
498   (let ((key-tmp (gensym)))
499     `(let ((,key-tmp (apply-key key ,elt)))
500       (cond (testp (funcall test ,item ,key-tmp))
501             (notp (not (funcall test-not ,item ,key-tmp)))
502             (t (funcall test ,item ,key-tmp))))))
503 \f
504 ;;;; substitution of expressions
505
506 (defun subst (new old tree &key key (test #'eql testp) (test-not nil notp))
507   #!+sb-doc
508   "Substitutes new for subtrees matching old."
509   (labels ((s (subtree)
510               (cond ((satisfies-the-test old subtree) new)
511                     ((atom subtree) subtree)
512                     (t (let ((car (s (car subtree)))
513                              (cdr (s (cdr subtree))))
514                          (if (and (eq car (car subtree))
515                                   (eq cdr (cdr subtree)))
516                              subtree
517                              (cons car cdr)))))))
518     (s tree)))
519
520 (defun subst-if (new test tree &key key)
521   #!+sb-doc
522   "Substitutes new for subtrees for which test is true."
523   (labels ((s (subtree)
524               (cond ((funcall test (apply-key key subtree)) new)
525                     ((atom subtree) subtree)
526                     (t (let ((car (s (car subtree)))
527                              (cdr (s (cdr subtree))))
528                          (if (and (eq car (car subtree))
529                                   (eq cdr (cdr subtree)))
530                              subtree
531                              (cons car cdr)))))))
532     (s tree)))
533
534 (defun subst-if-not (new test tree &key key)
535   #!+sb-doc
536   "Substitutes new for subtrees for which test is false."
537   (labels ((s (subtree)
538               (cond ((not (funcall test (apply-key key subtree))) new)
539                     ((atom subtree) subtree)
540                     (t (let ((car (s (car subtree)))
541                              (cdr (s (cdr subtree))))
542                          (if (and (eq car (car subtree))
543                                   (eq cdr (cdr subtree)))
544                              subtree
545                              (cons car cdr)))))))
546     (s tree)))
547
548 (defun nsubst (new old tree &key key (test #'eql testp) (test-not nil notp))
549   #!+sb-doc
550   "Substitutes new for subtrees matching old."
551   (labels ((s (subtree)
552               (cond ((satisfies-the-test old subtree) new)
553                     ((atom subtree) subtree)
554                     (t (do* ((last nil subtree)
555                              (subtree subtree (Cdr subtree)))
556                             ((atom subtree)
557                              (if (satisfies-the-test old subtree)
558                                  (setf (cdr last) new)))
559                          (if (satisfies-the-test old subtree)
560                              (return (setf (cdr last) new))
561                              (setf (car subtree) (s (car subtree)))))
562                        subtree))))
563     (s tree)))
564
565 (defun nsubst-if (new test tree &key key)
566   #!+sb-doc
567   "Substitutes new for subtrees of tree for which test is true."
568   (labels ((s (subtree)
569               (cond ((funcall test (apply-key key subtree)) new)
570                     ((atom subtree) subtree)
571                     (t (do* ((last nil subtree)
572                              (subtree subtree (Cdr subtree)))
573                             ((atom subtree)
574                              (if (funcall test (apply-key key subtree))
575                                  (setf (cdr last) new)))
576                          (if (funcall test (apply-key key subtree))
577                              (return (setf (cdr last) new))
578                              (setf (car subtree) (s (car subtree)))))
579                        subtree))))
580     (s tree)))
581
582 (defun nsubst-if-not (new test tree &key key)
583   #!+sb-doc
584   "Substitutes new for subtrees of tree for which test is false."
585   (labels ((s (subtree)
586               (cond ((not (funcall test (apply-key key subtree))) new)
587                     ((atom subtree) subtree)
588                     (t (do* ((last nil subtree)
589                              (subtree subtree (Cdr subtree)))
590                             ((atom subtree)
591                              (if (not (funcall test (apply-key key subtree)))
592                                  (setf (cdr last) new)))
593                          (if (not (funcall test (apply-key key subtree)))
594                              (return (setf (cdr last) new))
595                              (setf (car subtree) (s (car subtree)))))
596                        subtree))))
597     (s tree)))
598 \f
599 (defun sublis (alist tree &key key (test #'eql) (test-not nil notp))
600   #!+sb-doc
601   "Substitutes from alist into tree nondestructively."
602   (declare (inline assoc))
603   (labels ((s (subtree)
604              (let* ((key-val (apply-key key subtree))
605                     (assoc (if notp
606                                (assoc key-val alist :test-not test-not)
607                                (assoc key-val alist :test test))))
608                (cond (assoc (cdr assoc))
609                      ((atom subtree) subtree)
610                      (t (let ((car (s (car subtree)))
611                               (cdr (s (cdr subtree))))
612                           (if (and (eq car (car subtreE))
613                                    (eq cdr (cdr subtree)))
614                               subtree
615                               (cons car cdr))))))))
616     (s tree)))
617
618 ;;; These are in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
619 ;;; because they can be referenced in inline expansions.
620 (defmacro nsublis-macro ()
621   (let ((key-tmp (gensym)))
622     `(let ((,key-tmp (apply-key key subtree)))
623       (if notp
624           (assoc ,key-tmp alist :test-not test-not)
625           (assoc ,key-tmp alist :test test)))))
626
627 (defun nsublis (alist tree &key key (test #'eql) (test-not nil notp))
628   #!+sb-doc
629   "Substitutes new for subtrees matching old."
630   (declare (inline assoc))
631   (let (temp)
632     (labels ((s (subtree)
633                 (cond ((Setq temp (nsublis-macro))
634                        (cdr temp))
635                       ((atom subtree) subtree)
636                       (t (do* ((last nil subtree)
637                                (subtree subtree (Cdr subtree)))
638                               ((atom subtree)
639                                (if (setq temp (nsublis-macro))
640                                    (setf (cdr last) (cdr temp))))
641                            (if (setq temp (nsublis-macro))
642                                (return (setf (Cdr last) (Cdr temp)))
643                                (setf (car subtree) (s (car subtree)))))
644                          subtree))))
645       (s tree))))
646 \f
647 ;;;; functions for using lists as sets
648
649 (defun member (item list &key key (test #'eql testp) (test-not nil notp))
650   #!+sb-doc
651   "Returns tail of list beginning with first element satisfying EQLity,
652    :TEST, or :TEST-NOT with a given item."
653   (do ((list list (cdr list)))
654       ((null list) nil)
655     (let ((car (car list)))
656       (if (satisfies-the-test item car)
657           (return list)))))
658
659 (defun member-if (test list &key key)
660   #!+sb-doc
661   "Return tail of LIST beginning with first element satisfying TEST."
662   (do ((list list (Cdr list)))
663       ((endp list) nil)
664     (if (funcall test (apply-key key (car list)))
665         (return list))))
666
667 (defun member-if-not (test list &key key)
668   #!+sb-doc
669   "Return tail of LIST beginning with first element not satisfying TEST."
670   (do ((list list (cdr list)))
671       ((endp list) ())
672     (if (not (funcall test (apply-key key (car list))))
673         (return list))))
674
675 (defun tailp (object list)
676   #!+sb-doc
677   "Return true if OBJECT is the same as some tail of LIST, otherwise
678    returns false. LIST must be a proper list or a dotted list."
679   (do ((list list (cdr list)))
680       ((atom list) (eql list object))
681     (if (eql object list)
682         (return t))))
683
684 (defun adjoin (item list &key key (test #'eql) (test-not nil notp))
685   #!+sb-doc
686   "Add ITEM to LIST unless it is already a member"
687   (declare (inline member))
688   (if (let ((key-val (apply-key key item)))
689         (if notp
690             (member key-val list :test-not test-not :key key)
691             (member key-val list :test test :key key)))
692       list
693       (cons item list)))
694
695 ;;; This function assumes list2 is the result, adding to it from list1 as
696 ;;; necessary. List2 must initialize the result value, so the call to MEMBER
697 ;;; will apply the test to the elements from list1 and list2 in the correct
698 ;;; order.
699 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
700   #!+sb-doc
701   "Return the union of LIST1 and LIST2."
702   (declare (inline member))
703   (when (and testp notp) (error "Test and test-not both supplied."))
704   (let ((res list2))
705     (dolist (elt list1)
706       (unless (with-set-keys (member (apply-key key elt) list2))
707         (push elt res)))
708     res))
709
710 ;;; Destination and source are SETF-able and many-evaluable. Set the
711 ;;; SOURCE to the CDR, and "cons" the 1st elt of source to DESTINATION.
712 ;;;
713 ;;; FIXME: needs a more mnemonic name
714 (defmacro steve-splice (source destination)
715   `(let ((temp ,source))
716      (setf ,source (cdr ,source)
717            (cdr temp) ,destination
718            ,destination temp)))
719
720 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
721   #!+sb-doc
722   "Destructively return the union of LIST1 and LIST2."
723   (declare (inline member))
724   (if (and testp notp)
725       (error ":TEST and :TEST-NOT were both supplied."))
726   (let ((res list2)
727         (list1 list1))
728     (do ()
729         ((endp list1))
730       (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
731           (steve-splice list1 res)
732           (setf list1 (cdr list1))))
733     res))
734
735 (defun intersection (list1 list2 &key key
736                            (test #'eql testp) (test-not nil notp))
737   #!+sb-doc
738   "Return the intersection of LIST1 and LIST2."
739   (declare (inline member))
740   (if (and testp notp)
741       (error "Test and test-not both supplied."))
742   (let ((res nil))
743     (dolist (elt list1)
744       (if (with-set-keys (member (apply-key key elt) list2))
745           (push elt res)))
746     res))
747
748 (defun nintersection (list1 list2 &key key
749                             (test #'eql testp) (test-not nil notp))
750   #!+sb-doc
751   "Destructively return the intersection of LIST1 and LIST2."
752   (declare (inline member))
753   (if (and testp notp)
754       (error "Test and test-not both supplied."))
755   (let ((res nil)
756         (list1 list1))
757     (do () ((endp list1))
758       (if (with-set-keys (member (apply-key key (car list1)) list2))
759           (steve-splice list1 res)
760           (setq list1 (Cdr list1))))
761     res))
762
763 (defun set-difference (list1 list2 &key key
764                              (test #'eql testp) (test-not nil notp))
765   #!+sb-doc
766   "Return the elements of LIST1 which are not in LIST2."
767   (declare (inline member))
768   (if (and testp notp)
769       (error "Test and test-not both supplied."))
770   (if (null list2)
771       list1
772       (let ((res nil))
773         (dolist (elt list1)
774           (if (not (with-set-keys (member (apply-key key elt) list2)))
775               (push elt res)))
776         res)))
777
778 (defun nset-difference (list1 list2 &key key
779                               (test #'eql testp) (test-not nil notp))
780   #!+sb-doc
781   "Destructively return the elements of LIST1 which are not in LIST2."
782   (declare (inline member))
783   (if (and testp notp)
784       (error "Test and test-not both supplied."))
785   (let ((res nil)
786         (list1 list1))
787     (do () ((endp list1))
788       (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
789           (steve-splice list1 res)
790           (setq list1 (cdr list1))))
791     res))
792
793 (defun set-exclusive-or (list1 list2 &key key
794                                (test #'eql testp) (test-not nil notp))
795   #!+sb-doc
796   "Return new list of elements appearing exactly once in LIST1 and LIST2."
797   (declare (inline member))
798   (let ((result nil))
799     (dolist (elt list1)
800       (unless (with-set-keys (member (apply-key key elt) list2))
801         (setq result (cons elt result))))
802     (dolist (elt list2)
803       (unless (with-set-keys (member (apply-key key elt) list1))
804         (setq result (cons elt result))))
805     result))
806
807 ;;; The outer loop examines list1 while the inner loop examines list2.
808 ;;; If an element is found in list2 "equal" to the element in list1,
809 ;;; both are spliced out. When the end of list1 is reached, what is
810 ;;; left of list2 is tacked onto what is left of list1. The splicing
811 ;;; operation ensures that the correct operation is performed
812 ;;; depending on whether splice is at the top of the list or not
813 (defun nset-exclusive-or (list1 list2 &key (test #'eql) (test-not nil notp)
814                                 key)
815   #!+sb-doc
816   "Destructively return a list with elements which appear but once in LIST1
817    and LIST2."
818   (do ((list1 list1)
819        (list2 list2)
820        (x list1 (cdr x))
821        (splicex ()))
822       ((endp x)
823        (if (null splicex)
824            (setq list1 list2)
825            (rplacd splicex list2))
826        list1)
827     (do ((y list2 (cdr y))
828          (splicey ()))
829         ((endp y) (setq splicex x))
830       (cond ((let ((key-val-x (apply-key key (car x)))
831                    (key-val-y (apply-key key (Car y))))
832                (if notp
833                    (not (funcall test-not key-val-x key-val-y))
834                    (funcall test key-val-x key-val-y)))
835              (if (null splicex)
836                  (setq list1 (cdr x))
837                  (rplacd splicex (cdr x)))
838              (if (null splicey)
839                  (setq list2 (cdr y))
840                  (rplacd splicey (cdr y)))
841              (return ()))                       ; assume lists are really sets
842             (t (setq splicey y))))))
843
844 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
845   #!+sb-doc
846   "Return T if every element in LIST1 is also in LIST2."
847   (declare (inline member))
848   (dolist (elt list1)
849     (unless (with-set-keys (member (apply-key key elt) list2))
850       (return-from subsetp nil)))
851   T)
852 \f
853 ;;; functions that operate on association lists
854
855 (defun acons (key datum alist)
856   #!+sb-doc
857   "Construct a new alist by adding the pair (KEY . DATUM) to ALIST."
858   (cons (cons key datum) alist))
859
860 (defun pairlis (keys data &optional (alist '()))
861   #!+sb-doc
862   "Construct an association list from KEYS and DATA (adding to ALIST)."
863   (do ((x keys (cdr x))
864        (y data (cdr y)))
865       ((and (endp x) (endp y)) alist)
866     (if (or (endp x) (endp y))
867         (error "The lists of keys and data are of unequal length."))
868     (setq alist (acons (car x) (car y) alist))))
869
870 ;;; This is in the run-time environment (i.e. not wrapped in
871 ;;; EVAL-WHEN (COMPILE EVAL)) because these guys can be inline
872 ;;; expanded.
873 (defmacro assoc-guts (test-guy)
874   `(do ((alist alist (cdr alist)))
875        ((endp alist))
876      ;; FIXME: would be clearer as (WHEN (AND ..) ..)
877      (if (car alist)
878          (if ,test-guy (return (car alist))))))
879
880 (defun assoc (item alist &key key test test-not)
881   #!+sb-doc
882   "Returns the cons in ALIST whose car is equal (by a given test or EQL) to
883    the ITEM."
884   ;; FIXME: Shouldn't there be a check for existence of both TEST and TEST-NOT?
885   (cond (test
886          (if key
887              (assoc-guts (funcall test item (funcall key (caar alist))))
888              (assoc-guts (funcall test item (caar alist)))))
889         (test-not
890          (if key
891              (assoc-guts (not (funcall test-not item
892                                        (funcall key (caar alist)))))
893              (assoc-guts (not (funcall test-not item (caar alist))))))
894         (t
895          (if key
896              (assoc-guts (eql item (funcall key (caar alist))))
897              (assoc-guts (eql item (caar alist)))))))
898
899 (defun assoc-if (predicate alist &key key)
900   #!+sb-doc
901   "Returns the first cons in alist whose car satisfies the Predicate. If
902    key is supplied, apply it to the car of each cons before testing."
903   (if key
904       (assoc-guts (funcall predicate (funcall key (caar alist))))
905       (assoc-guts (funcall predicate (caar alist)))))
906
907 (defun assoc-if-not (predicate alist &key key)
908   #!+sb-doc
909   "Returns the first cons in ALIST whose car does not satisfy the PREDICATE.
910   If KEY is supplied, apply it to the car of each cons before testing."
911   (if key
912       (assoc-guts (not (funcall predicate (funcall key (caar alist)))))
913       (assoc-guts (not (funcall predicate (caar alist))))))
914
915 (defun rassoc (item alist &key key test test-not)
916   (declare (list alist))
917   #!+sb-doc
918   "Returns the cons in ALIST whose cdr is equal (by a given test or EQL) to
919    the ITEM."
920   (cond (test
921          (if key
922              (assoc-guts (funcall test item (funcall key (cdar alist))))
923              (assoc-guts (funcall test item (cdar alist)))))
924         (test-not
925          (if key
926              (assoc-guts (not (funcall test-not item
927                                        (funcall key (cdar alist)))))
928              (assoc-guts (not (funcall test-not item (cdar alist))))))
929         (t
930          (if key
931              (assoc-guts (eql item (funcall key (cdar alist))))
932              (assoc-guts (eql item (cdar alist)))))))
933
934 (defun rassoc-if (predicate alist &key key)
935   #!+sb-doc
936   "Returns the first cons in alist whose cdr satisfies the Predicate. If key
937   is supplied, apply it to the cdr of each cons before testing."
938   (if key
939       (assoc-guts (funcall predicate (funcall key (cdar alist))))
940       (assoc-guts (funcall predicate (cdar alist)))))
941
942 (defun rassoc-if-not (predicate alist &key key)
943   #!+sb-doc
944   "Returns the first cons in alist whose cdr does not satisfy the Predicate.
945   If key is supplied, apply it to the cdr of each cons before testing."
946   (if key
947       (assoc-guts (not (funcall predicate (funcall key (cdar alist)))))
948       (assoc-guts (not (funcall predicate (cdar alist))))))
949 \f
950 ;;;; mapping functions
951
952 (defun map1 (function original-arglists accumulate take-car)
953   #!+sb-doc
954   "This function is called by mapc, mapcar, mapcan, mapl, maplist, and mapcon.
955   It Maps function over the arglists in the appropriate way. It is done when any
956   of the arglists runs out. Until then, it CDRs down the arglists calling the
957   function and accumulating results as desired."
958
959   (let* ((arglists (copy-list original-arglists))
960          (ret-list (list nil))
961          (temp ret-list))
962     (do ((res nil)
963          (args '() '()))
964         ((dolist (x arglists nil) (if (null x) (return t)))
965          (if accumulate
966              (cdr ret-list)
967              (car original-arglists)))
968       (do ((l arglists (cdr l)))
969           ((null l))
970         (push (if take-car (caar l) (car l)) args)
971         (setf (car l) (cdar l)))
972       (setq res (apply function (nreverse args)))
973       (case accumulate
974         (:nconc (setq temp (last (nconc temp res))))
975         (:list (rplacd temp (list res))
976                (setq temp (cdr temp)))))))
977
978 (defun mapc (function list &rest more-lists)
979   #!+sb-doc
980   "Applies fn to successive elements of lists, returns its second argument."
981   (map1 function (cons list more-lists) nil t))
982
983 (defun mapcar (function list &rest more-lists)
984   #!+sb-doc
985   "Applies fn to successive elements of list, returns list of results."
986   (map1 function (cons list more-lists) :list t))
987
988 (defun mapcan (function list &rest more-lists)
989   #!+sb-doc
990   "Applies fn to successive elements of list, returns NCONC of results."
991   (map1 function (cons list more-lists) :nconc t))
992
993 (defun mapl (function list &rest more-lists)
994   #!+sb-doc
995   "Applies fn to successive CDRs of list, returns ()."
996   (map1 function (cons list more-lists) nil nil))
997
998 (defun maplist (function list &rest more-lists)
999   #!+sb-doc
1000   "Applies fn to successive CDRs of list, returns list of results."
1001   (map1 function (cons list more-lists) :list nil))
1002
1003 (defun mapcon (function list &rest more-lists)
1004   #!+sb-doc
1005   "Applies fn to successive CDRs of lists, returns NCONC of results."
1006   (map1 function (cons list more-lists) :nconc nil))