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