0.6.11.34:
[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 list-length nth %setnth nthcdr last make-list append
20           copy-list copy-alist copy-tree revappend nconc nreconc butlast
21           nbutlast ldiff member member-if member-if-not tailp adjoin union
22           nunion intersection nintersection set-difference nset-difference
23           set-exclusive-or nset-exclusive-or subsetp acons pairlis assoc
24           assoc-if assoc-if-not rassoc rassoc-if rassoc-if-not subst subst-if
25           subst-if-not nsubst nsubst-if nsubst-if-not sublis nsublis))
26
27 ;;; These functions perform basic list operations:
28 (defun car (list) #!+sb-doc "Returns the 1st object in a list." (car list))
29 (defun cdr (list)
30   #!+sb-doc "Returns all but the first object in a list."
31   (cdr list))
32 (defun cadr (list) #!+sb-doc "Returns the 2nd object in a list." (cadr list))
33 (defun cdar (list) #!+sb-doc "Returns the cdr of the 1st sublist." (cdar list))
34 (defun caar (list) #!+sb-doc "Returns the car of the 1st sublist." (caar list))
35 (defun cddr (list)
36   #!+sb-doc "Returns all but the 1st two objects of a list."
37   (cddr list))
38 (defun caddr (list)
39   #!+sb-doc "Returns the 1st object in the cddr of a list."
40   (caddr list))
41 (defun caadr (list)
42   #!+sb-doc "Returns the 1st object in the cadr of a list."
43   (caadr list))
44 (defun caaar (list)
45   #!+sb-doc "Returns the 1st object in the caar of a list."
46   (caaar list))
47 (defun cdaar (list)
48   #!+sb-doc "Returns the cdr of the caar of a list."
49   (cdaar list))
50 (defun cddar (list)
51   #!+sb-doc "Returns the cdr of the cdar of a list."
52   (cddar list))
53 (defun cdddr (list)
54   #!+sb-doc "Returns the cdr of the cddr of a list."
55   (cdddr list))
56 (defun cadar (list)
57   #!+sb-doc "Returns the car of the cdar of a list."
58   (cadar list))
59 (defun cdadr (list)
60   #!+sb-doc "Returns the cdr of the cadr of a list."
61   (cdadr list))
62 (defun caaaar (list)
63   #!+sb-doc "Returns the car of the caaar of a list."
64   (caaaar list))
65 (defun caaadr (list)
66   #!+sb-doc "Returns the car of the caadr of a list."
67   (caaadr list))
68 (defun caaddr (list)
69   #!+sb-doc "Returns the car of the caddr of a list."
70   (caaddr list))
71 (defun cadddr (list)
72   #!+sb-doc "Returns the car of the cdddr of a list."
73   (cadddr list))
74 (defun cddddr (list)
75   #!+sb-doc "Returns the cdr of the cdddr of a list."
76   (cddddr list))
77 (defun cdaaar (list)
78   #!+sb-doc "Returns the cdr of the caaar of a list."
79   (cdaaar list))
80 (defun cddaar (list)
81   #!+sb-doc "Returns the cdr of the cdaar of a list."
82   (cddaar list))
83 (defun cdddar (list)
84   #!+sb-doc "Returns the cdr of the cddar of a list."
85   (cdddar list))
86 (defun caadar (list)
87   #!+sb-doc "Returns the car of the cadar of a list."
88   (caadar list))
89 (defun cadaar (list)
90   #!+sb-doc "Returns the car of the cdaar of a list."
91   (cadaar list))
92 (defun cadadr (list)
93   #!+sb-doc "Returns the car of the cdadr of a list."
94   (cadadr list))
95 (defun caddar (list)
96   #!+sb-doc "Returns the car of the cddar of a list."
97   (caddar list))
98 (defun cdaadr (list)
99   #!+sb-doc "Returns the cdr of the caadr of a list."
100   (cdaadr list))
101 (defun cdadar (list)
102   #!+sb-doc "Returns the cdr of the cadar of a list."
103   (cdadar list))
104 (defun cdaddr (list)
105   #!+sb-doc "Returns the cdr of the caddr of a list."
106   (cdaddr list))
107 (defun cddadr (list)
108   #!+sb-doc "Returns the cdr of the cdadr of a list."
109   (cddadr list))
110 (defun cons (se1 se2)
111   #!+sb-doc "Returns a list with se1 as the car and se2 as the cdr."
112   (cons se1 se2))
113 \f
114 (declaim (maybe-inline tree-equal-test tree-equal-test-not))
115
116 (defun tree-equal-test-not (x y 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   (cond ((consp x)
127          (and (consp y)
128               (tree-equal-test (car x) (car y) test)
129               (tree-equal-test (cdr x) (cdr y) test)))
130         ((consp y) nil)
131         ((funcall test x y) t)
132         (t ())))
133
134 (defun tree-equal (x y &key (test #'eql) test-not)
135   #!+sb-doc
136   "Returns T if X and Y are isomorphic trees with identical leaves."
137   (if test-not
138       (tree-equal-test-not x y test-not)
139       (tree-equal-test x y test)))
140
141 (defun endp (object)
142   #!+sb-doc
143   "The recommended way to test for the end of a list. True if Object is nil,
144    false if Object is a cons, and an error for any other types of arguments."
145   (endp object))
146
147 (defun list-length (list)
148   #!+sb-doc
149   "Returns 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   "Returns 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   "Returns the 1st object in a list or NIL if the list is empty."
167   (car list))
168 (defun second (list)
169   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns 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   "Returns (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   "Returns (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            (n-remaining-to-copy (- n-conses-in-list n)))
412       (declare (type fixnum n-remaining-to-copy))
413       (when (plusp n-remaining-to-copy)
414         (do* ((result (list (first list)))
415               (rest (rest list) (rest rest))
416               (splice result))
417             ((zerop (decf n-remaining-to-copy))
418              result)
419           (setf splice
420                 (setf (cdr splice)
421                       (list (first rest))))))))
422   (defun nbutlast (list &optional (n 1))
423     (let ((n-conses-in-list (count-conses list)))
424       (unless (< n-conses-in-list n)
425         (setf (cdr (nthcdr (- n-conses-in-list n 1) list))
426               nil)
427         list))))
428
429 (defun ldiff (list object)
430   "Returns a new list, whose elements are those of List that appear before
431    Object. If Object is not a tail of List, a copy of List is returned.
432    List must be a proper list or a dotted list."
433   (do* ((list list (cdr list))
434         (result (list ()))
435         (splice result))
436        ((atom list)
437         (if (eql list object)
438             (cdr result)
439             (progn (rplacd splice list) (cdr result))))
440     (if (eql list object)
441         (return (cdr result))
442         (setq splice (cdr (rplacd splice (list (car list))))))))
443 \f
444 ;;;; functions to alter list structure
445
446 (defun rplaca (x y)
447   #!+sb-doc
448   "Changes the car of x to y and returns the new x."
449   (rplaca x y))
450
451 (defun rplacd (x y)
452   #!+sb-doc
453   "Changes the cdr of x to y and returns the new x."
454   (rplacd x y))
455
456 ;;; The following are for use by SETF.
457
458 (defun %rplaca (x val) (rplaca x val) val)
459
460 (defun %rplacd (x val) (rplacd x val) val)
461
462 (defun %setnth (n list newval)
463   (declare (type index n))
464   #!+sb-doc
465   "Sets the Nth element of List (zero based) to Newval."
466   (do ((count n (1- count))
467        (list list (cdr list)))
468       ((endp list)
469        (error "~S is too large an index for SETF of NTH." n))
470     (declare (fixnum count))
471     (when (<= count 0)
472       (rplaca list newval)
473       (return newval))))
474 \f
475 ;;;; :KEY arg optimization to save funcall of IDENTITY
476
477 ;;; APPLY-KEY saves us a function call sometimes.
478 ;;;    This is not wrapped in an (EVAL-WHEN (COMPILE EVAL) ..)
479 ;;;    because this is used in seq.lisp and sort.lisp.
480 (defmacro apply-key (key element)
481   `(if ,key
482        (funcall ,key ,element)
483        ,element))
484
485 (defun identity (thing)
486   #!+sb-doc
487   "Returns what was passed to it."
488   thing)
489
490 (defun complement (function)
491   #!+sb-doc
492   "Builds a new function that returns T whenever FUNCTION returns NIL and
493    NIL whenever FUNCTION returns non-NIL."
494   (lambda (&optional (arg0 nil arg0-p) (arg1 nil arg1-p) (arg2 nil arg2-p)
495                      &rest more-args)
496     (not (cond (more-args (apply function arg0 arg1 arg2 more-args))
497                (arg2-p (funcall function arg0 arg1 arg2))
498                (arg1-p (funcall function arg0 arg1))
499                (arg0-p (funcall function arg0))
500                (t (funcall function))))))
501
502 (defun constantly (value)
503   #!+sb-doc
504   "Return a function that always returns VALUE."
505   (lambda ()
506     ;; KLUDGE: This declaration is a hack to make the closure ignore
507     ;; all its arguments without consing a &REST list or anything.
508     ;; Perhaps once DYNAMIC-EXTENT is implemented we won't need to
509     ;; screw around with this kind of thing. -- WHN 2001-04-06
510     (declare (optimize (speed 3) (safety 0)))
511     value))
512 \f
513 ;;;; macros for (&KEY (KEY #'IDENTITY) (TEST #'EQL TESTP) (TEST-NOT NIL NOTP))
514
515 ;;; Use these with the following &KEY args:
516 (defmacro with-set-keys (funcall)
517   `(cond ((and testp notp) (error ":TEST and :TEST-NOT were both supplied."))
518          (notp ,(append funcall '(:key key :test-not test-not)))
519          (t ,(append funcall '(:key key :test test)))))
520
521 (defmacro satisfies-the-test (item elt)
522   (let ((key-tmp (gensym)))
523     `(let ((,key-tmp (apply-key key ,elt)))
524       (cond (testp (funcall test ,item ,key-tmp))
525             (notp (not (funcall test-not ,item ,key-tmp)))
526             (t (funcall test ,item ,key-tmp))))))
527 \f
528 ;;;; substitution of expressions
529
530 (defun subst (new old tree &key key (test #'eql testp) (test-not nil notp))
531   #!+sb-doc
532   "Substitutes new for subtrees matching old."
533   (labels ((s (subtree)
534               (cond ((satisfies-the-test old subtree) new)
535                     ((atom subtree) subtree)
536                     (t (let ((car (s (car subtree)))
537                              (cdr (s (cdr subtree))))
538                          (if (and (eq car (car subtree))
539                                   (eq cdr (cdr subtree)))
540                              subtree
541                              (cons car cdr)))))))
542     (s tree)))
543
544 (defun subst-if (new test tree &key key)
545   #!+sb-doc
546   "Substitutes new for subtrees for which test is true."
547   (labels ((s (subtree)
548               (cond ((funcall test (apply-key key subtree)) new)
549                     ((atom subtree) subtree)
550                     (t (let ((car (s (car subtree)))
551                              (cdr (s (cdr subtree))))
552                          (if (and (eq car (car subtree))
553                                   (eq cdr (cdr subtree)))
554                              subtree
555                              (cons car cdr)))))))
556     (s tree)))
557
558 (defun subst-if-not (new test tree &key key)
559   #!+sb-doc
560   "Substitutes new for subtrees for which test is false."
561   (labels ((s (subtree)
562               (cond ((not (funcall test (apply-key key subtree))) new)
563                     ((atom subtree) subtree)
564                     (t (let ((car (s (car subtree)))
565                              (cdr (s (cdr subtree))))
566                          (if (and (eq car (car subtree))
567                                   (eq cdr (cdr subtree)))
568                              subtree
569                              (cons car cdr)))))))
570     (s tree)))
571
572 (defun nsubst (new old tree &key key (test #'eql testp) (test-not nil notp))
573   #!+sb-doc
574   "Substitutes new for subtrees matching old."
575   (labels ((s (subtree)
576               (cond ((satisfies-the-test old subtree) new)
577                     ((atom subtree) subtree)
578                     (t (do* ((last nil subtree)
579                              (subtree subtree (Cdr subtree)))
580                             ((atom subtree)
581                              (if (satisfies-the-test old subtree)
582                                  (setf (cdr last) new)))
583                          (if (satisfies-the-test old subtree)
584                              (return (setf (cdr last) new))
585                              (setf (car subtree) (s (car subtree)))))
586                        subtree))))
587     (s tree)))
588
589 (defun nsubst-if (new test tree &key key)
590   #!+sb-doc
591   "Substitutes new for subtrees of tree for which test is true."
592   (labels ((s (subtree)
593               (cond ((funcall test (apply-key key subtree)) new)
594                     ((atom subtree) subtree)
595                     (t (do* ((last nil subtree)
596                              (subtree subtree (Cdr subtree)))
597                             ((atom subtree)
598                              (if (funcall test (apply-key key subtree))
599                                  (setf (cdr last) new)))
600                          (if (funcall test (apply-key key subtree))
601                              (return (setf (cdr last) new))
602                              (setf (car subtree) (s (car subtree)))))
603                        subtree))))
604     (s tree)))
605
606 (defun nsubst-if-not (new test tree &key key)
607   #!+sb-doc
608   "Substitutes new for subtrees of tree for which test is false."
609   (labels ((s (subtree)
610               (cond ((not (funcall test (apply-key key subtree))) new)
611                     ((atom subtree) subtree)
612                     (t (do* ((last nil subtree)
613                              (subtree subtree (Cdr subtree)))
614                             ((atom subtree)
615                              (if (not (funcall test (apply-key key subtree)))
616                                  (setf (cdr last) new)))
617                          (if (not (funcall test (apply-key key subtree)))
618                              (return (setf (cdr last) new))
619                              (setf (car subtree) (s (car subtree)))))
620                        subtree))))
621     (s tree)))
622 \f
623 (defun sublis (alist tree &key key (test #'eql) (test-not nil notp))
624   #!+sb-doc
625   "Substitutes from alist into tree nondestructively."
626   (declare (inline assoc))
627   (labels ((s (subtree)
628              (let* ((key-val (apply-key key subtree))
629                     (assoc (if notp
630                                (assoc key-val alist :test-not test-not)
631                                (assoc key-val alist :test test))))
632                (cond (assoc (cdr assoc))
633                      ((atom subtree) subtree)
634                      (t (let ((car (s (car subtree)))
635                               (cdr (s (cdr subtree))))
636                           (if (and (eq car (car subtreE))
637                                    (eq cdr (cdr subtree)))
638                               subtree
639                               (cons car cdr))))))))
640     (s tree)))
641
642 ;;; These are in run-time env (i.e. not wrapped in EVAL-WHEN (COMPILE EVAL))
643 ;;; because they can be referenced in inline expansions.
644 (defmacro nsublis-macro ()
645   (let ((key-tmp (gensym)))
646     `(let ((,key-tmp (apply-key key subtree)))
647       (if notp
648           (assoc ,key-tmp alist :test-not test-not)
649           (assoc ,key-tmp alist :test test)))))
650
651 (defun nsublis (alist tree &key key (test #'eql) (test-not nil notp))
652   #!+sb-doc
653   "Substitutes new for subtrees matching old."
654   (declare (inline assoc))
655   (let (temp)
656     (labels ((s (subtree)
657                 (cond ((Setq temp (nsublis-macro))
658                        (cdr temp))
659                       ((atom subtree) subtree)
660                       (t (do* ((last nil subtree)
661                                (subtree subtree (Cdr subtree)))
662                               ((atom subtree)
663                                (if (setq temp (nsublis-macro))
664                                    (setf (cdr last) (cdr temp))))
665                            (if (setq temp (nsublis-macro))
666                                (return (setf (Cdr last) (Cdr temp)))
667                                (setf (car subtree) (s (car subtree)))))
668                          subtree))))
669       (s tree))))
670 \f
671 ;;;; functions for using lists as sets
672
673 (defun member (item list &key key (test #'eql testp) (test-not nil notp))
674   #!+sb-doc
675   "Returns tail of list beginning with first element satisfying EQLity,
676    :test, or :test-not with a given item."
677   (do ((list list (cdr list)))
678       ((null list) nil)
679     (let ((car (car list)))
680       (if (satisfies-the-test item car)
681           (return list)))))
682
683 (defun member-if (test list &key key)
684   #!+sb-doc
685   "Returns tail of list beginning with first element satisfying test(element)"
686   (do ((list list (Cdr list)))
687       ((endp list) nil)
688     (if (funcall test (apply-key key (car list)))
689         (return list))))
690
691 (defun member-if-not (test list &key key)
692   #!+sb-doc
693   "Returns tail of list beginning with first element not satisfying test(el)"
694   (do ((list list (cdr list)))
695       ((endp list) ())
696     (if (not (funcall test (apply-key key (car list))))
697         (return list))))
698
699 (defun tailp (object list)
700   #!+sb-doc
701   "Returns true if Object is the same as some tail of List, otherwise
702    returns false. List must be a proper list or a dotted list."
703   (do ((list list (cdr list)))
704       ((atom list) (eql list object))
705     (if (eql object list)
706         (return t))))
707
708 (defun adjoin (item list &key key (test #'eql) (test-not nil notp))
709   #!+sb-doc
710   "Add item to list unless it is already a member"
711   (declare (inline member))
712   (if (let ((key-val (apply-key key item)))
713         (if notp
714             (member key-val list :test-not test-not :key key)
715             (member key-val list :test test :key key)))
716       list
717       (cons item list)))
718
719 ;;; This function assumes list2 is the result, adding to it from list1 as
720 ;;; necessary. List2 must initialize the result value, so the call to MEMBER
721 ;;; will apply the test to the elements from list1 and list2 in the correct
722 ;;; order.
723 (defun union (list1 list2 &key key (test #'eql testp) (test-not nil notp))
724   #!+sb-doc
725   "Returns the union of list1 and list2."
726   (declare (inline member))
727   (when (and testp notp) (error "Test and test-not both supplied."))
728   (let ((res list2))
729     (dolist (elt list1)
730       (unless (with-set-keys (member (apply-key key elt) list2))
731         (push elt res)))
732     res))
733
734 ;;; Destination and source are setf-able and many-evaluable. Sets the source
735 ;;; to the cdr, and "conses" the 1st elt of source to destination.
736 ;;;
737 ;;; FIXME: needs a more mnemonic name
738 (defmacro steve-splice (source destination)
739   `(let ((temp ,source))
740      (setf ,source (cdr ,source)
741            (cdr temp) ,destination
742            ,destination temp)))
743
744 (defun nunion (list1 list2 &key key (test #'eql testp) (test-not nil notp))
745   #!+sb-doc
746   "Destructively returns the union list1 and list2."
747   (declare (inline member))
748   (if (and testp notp)
749       (error "Test and test-not both supplied."))
750   (let ((res list2)
751         (list1 list1))
752     (do ()
753         ((endp list1))
754       (if (not (with-set-keys (member (apply-key key (car list1)) list2)))
755           (steve-splice list1 res)
756           (setf list1 (cdr list1))))
757     res))
758
759 (defun intersection (list1 list2 &key key
760                            (test #'eql testp) (test-not nil notp))
761   #!+sb-doc
762   "Returns the intersection of list1 and list2."
763   (declare (inline member))
764   (if (and testp notp)
765       (error "Test and test-not both supplied."))
766   (let ((res nil))
767     (dolist (elt list1)
768       (if (with-set-keys (member (apply-key key elt) list2))
769           (push elt res)))
770     res))
771
772 (defun nintersection (list1 list2 &key key
773                             (test #'eql testp) (test-not nil notp))
774   #!+sb-doc
775   "Destructively returns the intersection of list1 and list2."
776   (declare (inline member))
777   (if (and testp notp)
778       (error "Test and test-not both supplied."))
779   (let ((res nil)
780         (list1 list1))
781     (do () ((endp list1))
782       (if (with-set-keys (member (apply-key key (car list1)) list2))
783           (steve-splice list1 res)
784           (setq list1 (Cdr list1))))
785     res))
786
787 (defun set-difference (list1 list2 &key key
788                              (test #'eql testp) (test-not nil notp))
789   #!+sb-doc
790   "Returns the elements of list1 which are not in list2."
791   (declare (inline member))
792   (if (and testp notp)
793       (error "Test and test-not both supplied."))
794   (if (null list2)
795       list1
796       (let ((res nil))
797         (dolist (elt list1)
798           (if (not (with-set-keys (member (apply-key key elt) list2)))
799               (push elt res)))
800         res)))
801
802 (defun nset-difference (list1 list2 &key key
803                               (test #'eql testp) (test-not nil notp))
804   #!+sb-doc
805   "Destructively returns the elements of list1 which are not in list2."
806   (declare (inline member))
807   (if (and testp notp)
808       (error "Test and test-not both supplied."))
809   (let ((res nil)
810         (list1 list1))
811     (do () ((endp list1))
812       (if (not (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-exclusive-or (list1 list2 &key key
818                                (test #'eql testp) (test-not nil notp))
819   #!+sb-doc
820   "Returns new list of elements appearing exactly once in list1 and list2."
821   (declare (inline member))
822   (let ((result nil))
823     (dolist (elt list1)
824       (unless (with-set-keys (member (apply-key key elt) list2))
825         (setq result (cons elt result))))
826     (dolist (elt list2)
827       (unless (with-set-keys (member (apply-key key elt) list1))
828         (setq result (cons elt result))))
829     result))
830
831 ;;; The outer loop examines list1 while the inner loop examines list2. If an
832 ;;; element is found in list2 "equal" to the element in list1, both are
833 ;;; spliced out. When the end of list1 is reached, what is left of list2 is
834 ;;; tacked onto what is left of list1. The splicing operation ensures that
835 ;;; the correct operation is performed depending on whether splice is at the
836 ;;; top of the list or not
837
838 (defun nset-exclusive-or (list1 list2 &key (test #'eql) (test-not nil notp)
839                                 key)
840   #!+sb-doc
841   "Destructively return a list with elements which appear but once in list1
842    and list2."
843   (do ((list1 list1)
844        (list2 list2)
845        (x list1 (cdr x))
846        (splicex ()))
847       ((endp x)
848        (if (null splicex)
849            (setq list1 list2)
850            (rplacd splicex list2))
851        list1)
852     (do ((y list2 (cdr y))
853          (splicey ()))
854         ((endp y) (setq splicex x))
855       (cond ((let ((key-val-x (apply-key key (car x)))
856                    (key-val-y (apply-key key (Car y))))
857                (if notp
858                    (not (funcall test-not key-val-x key-val-y))
859                    (funcall test key-val-x key-val-y)))
860              (if (null splicex)
861                  (setq list1 (cdr x))
862                  (rplacd splicex (cdr x)))
863              (if (null splicey)
864                  (setq list2 (cdr y))
865                  (rplacd splicey (cdr y)))
866              (return ()))                       ; assume lists are really sets
867             (t (setq splicey y))))))
868
869 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
870   #!+sb-doc
871   "Returns T if every element in list1 is also in list2."
872   (declare (inline member))
873   (dolist (elt list1)
874     (unless (with-set-keys (member (apply-key key elt) list2))
875       (return-from subsetp nil)))
876   T)
877 \f
878 ;;; functions that operate on association lists
879
880 (defun acons (key datum alist)
881   #!+sb-doc
882   "Construct a new alist by adding the pair (key . datum) to alist"
883   (cons (cons key datum) alist))
884
885 (defun pairlis (keys data &optional (alist '()))
886   #!+sb-doc
887   "Construct an association list from keys and data (adding to alist)"
888   (do ((x keys (cdr x))
889        (y data (cdr y)))
890       ((and (endp x) (endp y)) alist)
891     (if (or (endp x) (endp y))
892         (error "The lists of keys and data are of unequal length."))
893     (setq alist (acons (car x) (car y) alist))))
894
895 ;;; This is in the run-time environment (i.e. not wrapped in
896 ;;; EVAL-WHEN (COMPILE EVAL)) because these guys can be inline
897 ;;; expanded.
898 (defmacro assoc-guts (test-guy)
899   `(do ((alist alist (cdr alist)))
900        ((endp alist))
901      ;; FIXME: would be clearer as (WHEN (AND ..) ..)
902      (if (car alist)
903          (if ,test-guy (return (car alist))))))
904
905 (defun assoc (item alist &key key test test-not)
906   #!+sb-doc
907   "Returns the cons in ALIST whose car is equal (by a given test or EQL) to
908    the ITEM."
909   ;; FIXME: Shouldn't there be a check for existence of both TEST and TEST-NOT?
910   (cond (test
911          (if key
912              (assoc-guts (funcall test item (funcall key (caar alist))))
913              (assoc-guts (funcall test item (caar alist)))))
914         (test-not
915          (if key
916              (assoc-guts (not (funcall test-not item
917                                        (funcall key (caar alist)))))
918              (assoc-guts (not (funcall test-not item (caar alist))))))
919         (t
920          (if key
921              (assoc-guts (eql item (funcall key (caar alist))))
922              (assoc-guts (eql item (caar alist)))))))
923
924 (defun assoc-if (predicate alist &key key)
925   #!+sb-doc
926   "Returns the first cons in alist whose car satisfies the Predicate. If
927    key is supplied, apply it to the car of each cons before testing."
928   (if key
929       (assoc-guts (funcall predicate (funcall key (caar alist))))
930       (assoc-guts (funcall predicate (caar alist)))))
931
932 (defun assoc-if-not (predicate alist &key key)
933   #!+sb-doc
934   "Returns the first cons in alist whose car does not satisfiy the Predicate.
935   If key is supplied, apply it to the car of each cons before testing."
936   (if key
937       (assoc-guts (not (funcall predicate (funcall key (caar alist)))))
938       (assoc-guts (not (funcall predicate (caar alist))))))
939
940 (defun rassoc (item alist &key key test test-not)
941   (declare (list alist))
942   #!+sb-doc
943   "Returns the cons in alist whose cdr is equal (by a given test or EQL) to
944    the Item."
945   (cond (test
946          (if key
947              (assoc-guts (funcall test item (funcall key (cdar alist))))
948              (assoc-guts (funcall test item (cdar alist)))))
949         (test-not
950          (if key
951              (assoc-guts (not (funcall test-not item
952                                        (funcall key (cdar alist)))))
953              (assoc-guts (not (funcall test-not item (cdar alist))))))
954         (t
955          (if key
956              (assoc-guts (eql item (funcall key (cdar alist))))
957              (assoc-guts (eql item (cdar alist)))))))
958
959 (defun rassoc-if (predicate alist &key key)
960   #!+sb-doc
961   "Returns the first cons in alist whose cdr satisfies the Predicate. If key
962   is supplied, apply it to the cdr of each cons before testing."
963   (if key
964       (assoc-guts (funcall predicate (funcall key (cdar alist))))
965       (assoc-guts (funcall predicate (cdar alist)))))
966
967 (defun rassoc-if-not (predicate alist &key key)
968   #!+sb-doc
969   "Returns the first cons in alist whose cdr does not satisfy the Predicate.
970   If key is supplied, apply it to the cdr of each cons before testing."
971   (if key
972       (assoc-guts (not (funcall predicate (funcall key (cdar alist)))))
973       (assoc-guts (not (funcall predicate (cdar alist))))))
974 \f
975 ;;;; mapping functions
976
977 (defun map1 (function original-arglists accumulate take-car)
978   #!+sb-doc
979   "This function is called by mapc, mapcar, mapcan, mapl, maplist, and mapcon.
980   It Maps function over the arglists in the appropriate way. It is done when any
981   of the arglists runs out. Until then, it CDRs down the arglists calling the
982   function and accumulating results as desired."
983
984   (let* ((arglists (copy-list original-arglists))
985          (ret-list (list nil))
986          (temp ret-list))
987     (do ((res nil)
988          (args '() '()))
989         ((dolist (x arglists nil) (if (null x) (return t)))
990          (if accumulate
991              (cdr ret-list)
992              (car original-arglists)))
993       (do ((l arglists (cdr l)))
994           ((null l))
995         (push (if take-car (caar l) (car l)) args)
996         (setf (car l) (cdar l)))
997       (setq res (apply function (nreverse args)))
998       (case accumulate
999         (:nconc (setq temp (last (nconc temp res))))
1000         (:list (rplacd temp (list res))
1001                (setq temp (cdr temp)))))))
1002
1003 (defun mapc (function list &rest more-lists)
1004   #!+sb-doc
1005   "Applies fn to successive elements of lists, returns its second argument."
1006   (map1 function (cons list more-lists) nil t))
1007
1008 (defun mapcar (function list &rest more-lists)
1009   #!+sb-doc
1010   "Applies fn to successive elements of list, returns list of results."
1011   (map1 function (cons list more-lists) :list t))
1012
1013 (defun mapcan (function list &rest more-lists)
1014   #!+sb-doc
1015   "Applies fn to successive elements of list, returns NCONC of results."
1016   (map1 function (cons list more-lists) :nconc t))
1017
1018 (defun mapl (function list &rest more-lists)
1019   #!+sb-doc
1020   "Applies fn to successive CDRs of list, returns ()."
1021   (map1 function (cons list more-lists) nil nil))
1022
1023 (defun maplist (function list &rest more-lists)
1024   #!+sb-doc
1025   "Applies fn to successive CDRs of list, returns list of results."
1026   (map1 function (cons list more-lists) :list nil))
1027
1028 (defun mapcon (function list &rest more-lists)
1029   #!+sb-doc
1030   "Applies fn to successive CDRs of lists, returns NCONC of results."
1031   (map1 function (cons list more-lists) :nconc nil))