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