4f78953183962e8fb1eb43e27ee544d31d7c0574
[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   "Return tail of LIST beginning with first element satisfying TEST."
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   "Return tail of LIST beginning with first element not satisfying TEST."
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   "Return 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   "Return 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. Set the
735 ;;; SOURCE to the CDR, and "cons" 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 return the union of LIST1 and LIST2."
747   (declare (inline member))
748   (if (and testp notp)
749       (error ":TEST and :TEST-NOT were 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   "Return 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 return 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   "Return 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 return 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   "Return 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.
832 ;;; If an element is found in list2 "equal" to the element in list1,
833 ;;; both are spliced out. When the end of list1 is reached, what is
834 ;;; left of list2 is tacked onto what is left of list1. The splicing
835 ;;; operation ensures that the correct operation is performed
836 ;;; depending on whether splice is at the top of the list or not
837 (defun nset-exclusive-or (list1 list2 &key (test #'eql) (test-not nil notp)
838                                 key)
839   #!+sb-doc
840   "Destructively return a list with elements which appear but once in LIST1
841    and LIST2."
842   (do ((list1 list1)
843        (list2 list2)
844        (x list1 (cdr x))
845        (splicex ()))
846       ((endp x)
847        (if (null splicex)
848            (setq list1 list2)
849            (rplacd splicex list2))
850        list1)
851     (do ((y list2 (cdr y))
852          (splicey ()))
853         ((endp y) (setq splicex x))
854       (cond ((let ((key-val-x (apply-key key (car x)))
855                    (key-val-y (apply-key key (Car y))))
856                (if notp
857                    (not (funcall test-not key-val-x key-val-y))
858                    (funcall test key-val-x key-val-y)))
859              (if (null splicex)
860                  (setq list1 (cdr x))
861                  (rplacd splicex (cdr x)))
862              (if (null splicey)
863                  (setq list2 (cdr y))
864                  (rplacd splicey (cdr y)))
865              (return ()))                       ; assume lists are really sets
866             (t (setq splicey y))))))
867
868 (defun subsetp (list1 list2 &key key (test #'eql testp) (test-not nil notp))
869   #!+sb-doc
870   "Return T if every element in LIST1 is also in LIST2."
871   (declare (inline member))
872   (dolist (elt list1)
873     (unless (with-set-keys (member (apply-key key elt) list2))
874       (return-from subsetp nil)))
875   T)
876 \f
877 ;;; functions that operate on association lists
878
879 (defun acons (key datum alist)
880   #!+sb-doc
881   "Construct a new alist by adding the pair (KEY . DATUM) to ALIST."
882   (cons (cons key datum) alist))
883
884 (defun pairlis (keys data &optional (alist '()))
885   #!+sb-doc
886   "Construct an association list from KEYS and DATA (adding to ALIST)."
887   (do ((x keys (cdr x))
888        (y data (cdr y)))
889       ((and (endp x) (endp y)) alist)
890     (if (or (endp x) (endp y))
891         (error "The lists of keys and data are of unequal length."))
892     (setq alist (acons (car x) (car y) alist))))
893
894 ;;; This is in the run-time environment (i.e. not wrapped in
895 ;;; EVAL-WHEN (COMPILE EVAL)) because these guys can be inline
896 ;;; expanded.
897 (defmacro assoc-guts (test-guy)
898   `(do ((alist alist (cdr alist)))
899        ((endp alist))
900      ;; FIXME: would be clearer as (WHEN (AND ..) ..)
901      (if (car alist)
902          (if ,test-guy (return (car alist))))))
903
904 (defun assoc (item alist &key key test test-not)
905   #!+sb-doc
906   "Returns the cons in ALIST whose car is equal (by a given test or EQL) to
907    the ITEM."
908   ;; FIXME: Shouldn't there be a check for existence of both TEST and TEST-NOT?
909   (cond (test
910          (if key
911              (assoc-guts (funcall test item (funcall key (caar alist))))
912              (assoc-guts (funcall test item (caar alist)))))
913         (test-not
914          (if key
915              (assoc-guts (not (funcall test-not item
916                                        (funcall key (caar alist)))))
917              (assoc-guts (not (funcall test-not item (caar alist))))))
918         (t
919          (if key
920              (assoc-guts (eql item (funcall key (caar alist))))
921              (assoc-guts (eql item (caar alist)))))))
922
923 (defun assoc-if (predicate alist &key key)
924   #!+sb-doc
925   "Returns the first cons in alist whose car satisfies the Predicate. If
926    key is supplied, apply it to the car of each cons before testing."
927   (if key
928       (assoc-guts (funcall predicate (funcall key (caar alist))))
929       (assoc-guts (funcall predicate (caar alist)))))
930
931 (defun assoc-if-not (predicate alist &key key)
932   #!+sb-doc
933   "Returns the first cons in alist whose car does not satisfiy the Predicate.
934   If key is supplied, apply it to the car of each cons before testing."
935   (if key
936       (assoc-guts (not (funcall predicate (funcall key (caar alist)))))
937       (assoc-guts (not (funcall predicate (caar alist))))))
938
939 (defun rassoc (item alist &key key test test-not)
940   (declare (list alist))
941   #!+sb-doc
942   "Returns the cons in alist whose cdr is equal (by a given test or EQL) to
943    the Item."
944   (cond (test
945          (if key
946              (assoc-guts (funcall test item (funcall key (cdar alist))))
947              (assoc-guts (funcall test item (cdar alist)))))
948         (test-not
949          (if key
950              (assoc-guts (not (funcall test-not item
951                                        (funcall key (cdar alist)))))
952              (assoc-guts (not (funcall test-not item (cdar alist))))))
953         (t
954          (if key
955              (assoc-guts (eql item (funcall key (cdar alist))))
956              (assoc-guts (eql item (cdar alist)))))))
957
958 (defun rassoc-if (predicate alist &key key)
959   #!+sb-doc
960   "Returns the first cons in alist whose cdr satisfies the Predicate. If key
961   is supplied, apply it to the cdr of each cons before testing."
962   (if key
963       (assoc-guts (funcall predicate (funcall key (cdar alist))))
964       (assoc-guts (funcall predicate (cdar alist)))))
965
966 (defun rassoc-if-not (predicate alist &key key)
967   #!+sb-doc
968   "Returns the first cons in alist whose cdr does not satisfy the Predicate.
969   If key is supplied, apply it to the cdr of each cons before testing."
970   (if key
971       (assoc-guts (not (funcall predicate (funcall key (cdar alist)))))
972       (assoc-guts (not (funcall predicate (cdar alist))))))
973 \f
974 ;;;; mapping functions
975
976 (defun map1 (function original-arglists accumulate take-car)
977   #!+sb-doc
978   "This function is called by mapc, mapcar, mapcan, mapl, maplist, and mapcon.
979   It Maps function over the arglists in the appropriate way. It is done when any
980   of the arglists runs out. Until then, it CDRs down the arglists calling the
981   function and accumulating results as desired."
982
983   (let* ((arglists (copy-list original-arglists))
984          (ret-list (list nil))
985          (temp ret-list))
986     (do ((res nil)
987          (args '() '()))
988         ((dolist (x arglists nil) (if (null x) (return t)))
989          (if accumulate
990              (cdr ret-list)
991              (car original-arglists)))
992       (do ((l arglists (cdr l)))
993           ((null l))
994         (push (if take-car (caar l) (car l)) args)
995         (setf (car l) (cdar l)))
996       (setq res (apply function (nreverse args)))
997       (case accumulate
998         (:nconc (setq temp (last (nconc temp res))))
999         (:list (rplacd temp (list res))
1000                (setq temp (cdr temp)))))))
1001
1002 (defun mapc (function list &rest more-lists)
1003   #!+sb-doc
1004   "Applies fn to successive elements of lists, returns its second argument."
1005   (map1 function (cons list more-lists) nil t))
1006
1007 (defun mapcar (function list &rest more-lists)
1008   #!+sb-doc
1009   "Applies fn to successive elements of list, returns list of results."
1010   (map1 function (cons list more-lists) :list t))
1011
1012 (defun mapcan (function list &rest more-lists)
1013   #!+sb-doc
1014   "Applies fn to successive elements of list, returns NCONC of results."
1015   (map1 function (cons list more-lists) :nconc t))
1016
1017 (defun mapl (function list &rest more-lists)
1018   #!+sb-doc
1019   "Applies fn to successive CDRs of list, returns ()."
1020   (map1 function (cons list more-lists) nil nil))
1021
1022 (defun maplist (function list &rest more-lists)
1023   #!+sb-doc
1024   "Applies fn to successive CDRs of list, returns list of results."
1025   (map1 function (cons list more-lists) :list nil))
1026
1027 (defun mapcon (function list &rest more-lists)
1028   #!+sb-doc
1029   "Applies fn to successive CDRs of lists, returns NCONC of results."
1030   (map1 function (cons list more-lists) :nconc nil))