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