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