0.7.4.3:
[sbcl.git] / src / code / seq.lisp
1 ;;;; generic SEQUENCEs
2 ;;;;
3 ;;;; KLUDGE: comment from original CMU CL source:
4 ;;;;   Be careful when modifying code. A lot of the structure of the
5 ;;;;   code is affected by the fact that compiler transforms use the
6 ;;;;   lower level support functions. If transforms are written for
7 ;;;;   some sequence operation, note how the END argument is handled
8 ;;;;   in other operations with transforms.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!IMPL")
20 \f
21 ;;;; utilities
22
23 (eval-when (:compile-toplevel)
24
25 ;;; SEQ-DISPATCH does an efficient type-dispatch on the given SEQUENCE.
26 ;;;
27 ;;; FIXME: It might be worth making three cases here, LIST,
28 ;;; SIMPLE-VECTOR, and VECTOR, instead of the current LIST and VECTOR.
29 ;;; It tend to make code run faster but be bigger; some benchmarking
30 ;;; is needed to decide.
31 (sb!xc:defmacro seq-dispatch (sequence list-form array-form)
32   `(if (listp ,sequence)
33        ,list-form
34        ,array-form))
35
36 (sb!xc:defmacro make-sequence-like (sequence length)
37   #!+sb-doc
38   "Return a sequence of the same type as SEQUENCE and the given LENGTH."
39   `(make-sequence-of-type (type-of ,sequence) ,length))
40
41 (sb!xc:defmacro type-specifier-atom (type)
42   #!+sb-doc "Return the broad class of which TYPE is a specific subclass."
43   `(if (atom ,type) ,type (car ,type)))
44
45 ) ; EVAL-WHEN
46
47 ;;; It's possible with some sequence operations to declare the length
48 ;;; of a result vector, and to be safe, we really ought to verify that
49 ;;; the actual result has the declared length.
50 (defun vector-of-checked-length-given-length (vector declared-length)
51   (declare (type vector vector))
52   (declare (type index declared-length))
53   (let ((actual-length (length vector)))
54     (unless (= actual-length declared-length)
55       (error 'simple-type-error
56              :datum vector
57              :expected-type `(vector ,declared-length)
58              :format-control
59              "Vector length (~W) doesn't match declared length (~W)."
60              :format-arguments (list actual-length declared-length))))
61   vector)
62 (defun sequence-of-checked-length-given-type (sequence result-type)
63   (let ((ctype (specifier-type result-type)))
64     (if (not (array-type-p ctype))
65         sequence
66         (let ((declared-length (first (array-type-dimensions ctype))))
67           (if (eq declared-length '*)
68               sequence
69               (vector-of-checked-length-given-length sequence
70                                                      declared-length))))))
71
72 ;;; Given an arbitrary type specifier, return a sane sequence type
73 ;;; specifier that we can directly match.
74 (defun result-type-or-lose (type &optional nil-ok)
75   (let ((type (specifier-type type)))
76     (cond
77       ((eq type *empty-type*)
78        (if nil-ok
79            nil
80            (error 'simple-type-error
81                   :datum type
82                   :expected-type '(or vector cons)
83                   :format-control
84                   "A NIL output type is invalid for this sequence function."
85                   :format-arguments ())))
86       ((dolist (seq-type '(list string simple-vector bit-vector))
87          (when (csubtypep type (specifier-type seq-type))
88            (return seq-type))))
89       ((csubtypep type (specifier-type 'vector))
90        (type-specifier type))
91       (t
92        (error 'simple-type-error
93               :datum type
94               :expected-type 'sequence
95               :format-control
96               "~S is not a legal type specifier for sequence functions."
97               :format-arguments (list type))))))
98
99 (defun signal-index-too-large-error (sequence index)
100   (let* ((length (length sequence))
101          (max-index (and (plusp length) (1- length))))
102     (error 'index-too-large-error
103            :datum index
104            :expected-type (if max-index
105                               `(integer 0 ,max-index)
106                               ;; This seems silly, is there something better?
107                               '(integer (0) (0))))))
108
109 (defun make-sequence-of-type (type length)
110   #!+sb-doc "Return a sequence of the given TYPE and LENGTH."
111   (declare (fixnum length))
112   (case (type-specifier-atom type)
113     (list (make-list length))
114     ((bit-vector simple-bit-vector) (make-array length :element-type '(mod 2)))
115     ((string simple-string base-string simple-base-string)
116      (make-string length))
117     (simple-vector (make-array length))
118     ((array simple-array vector)
119      (if (listp type)
120          (make-array length :element-type (cadr type))
121          (make-array length)))
122     (t
123      (make-sequence-of-type (result-type-or-lose type) length))))
124 \f
125 (defun elt (sequence index)
126   #!+sb-doc "Return the element of SEQUENCE specified by INDEX."
127   (etypecase sequence
128     (list
129      (do ((count index (1- count))
130           (list sequence (cdr list)))
131          ((= count 0)
132           (if (endp list)
133               (signal-index-too-large-error sequence index)
134               (car list)))
135        (declare (type (integer 0) count))))
136     (vector
137      (when (>= index (length sequence))
138        (signal-index-too-large-error sequence index))
139      (aref sequence index))))
140
141 (defun %setelt (sequence index newval)
142   #!+sb-doc "Store NEWVAL as the component of SEQUENCE specified by INDEX."
143   (etypecase sequence
144     (list
145      (do ((count index (1- count))
146           (seq sequence))
147          ((= count 0) (rplaca seq newval) newval)
148        (declare (fixnum count))
149        (if (atom (cdr seq))
150            (signal-index-too-large-error sequence index)
151            (setq seq (cdr seq)))))
152     (vector
153      (when (>= index (length sequence))
154        (signal-index-too-large-error sequence index))
155      (setf (aref sequence index) newval))))
156
157 (defun length (sequence)
158   #!+sb-doc "Return an integer that is the length of SEQUENCE."
159   (etypecase sequence
160     (vector (length (truly-the vector sequence)))
161     (list (length (truly-the list sequence)))))
162
163 (defun make-sequence (type length &key (initial-element NIL iep))
164   #!+sb-doc
165   "Return a sequence of the given TYPE and LENGTH, with elements initialized
166   to :INITIAL-ELEMENT."
167   (declare (fixnum length))
168   (let ((type (specifier-type type)))
169     (cond ((csubtypep type (specifier-type 'list))
170            (make-list length :initial-element initial-element))
171           ((csubtypep type (specifier-type 'string))
172            (if iep
173                (make-string length :initial-element initial-element)
174                (make-string length)))
175           ((csubtypep type (specifier-type 'simple-vector))
176            (make-array length :initial-element initial-element))
177           ((csubtypep type (specifier-type 'bit-vector))
178            (if iep
179                (make-array length :element-type '(mod 2)
180                            :initial-element initial-element)
181                (make-array length :element-type '(mod 2))))
182           ((csubtypep type (specifier-type 'vector))
183            (if (typep type 'array-type)
184                (let ((etype (type-specifier
185                              (array-type-specialized-element-type type)))
186                      (vlen (car (array-type-dimensions type))))
187                  (if (and (numberp vlen) (/= vlen length))
188                    (error 'simple-type-error
189                           ;; These two are under-specified by ANSI.
190                           :datum (type-specifier type)
191                           :expected-type (type-specifier type)
192                           :format-control
193                           "The length of ~S does not match the specified ~
194                            length=~S."
195                           :format-arguments
196                           (list (type-specifier type) length)))
197                  (if iep
198                      (make-array length :element-type etype
199                                  :initial-element initial-element)
200                      (make-array length :element-type etype)))
201                (make-array length :initial-element initial-element)))
202           (t (error 'simple-type-error
203                     :datum type
204                     :expected-type 'sequence
205                     :format-control "~S is a bad type specifier for sequences."
206                     :format-arguments (list type))))))
207 \f
208 ;;;; SUBSEQ
209 ;;;;
210 ;;;; The support routines for SUBSEQ are used by compiler transforms, so we
211 ;;;; worry about dealing with END being supplied or defaulting to NIL
212 ;;;; at this level.
213
214 (defun vector-subseq* (sequence start &optional end)
215   (declare (type vector sequence))
216   (declare (type fixnum start))
217   (declare (type (or null fixnum) end))
218   (when (null end) (setf end (length sequence)))
219   (do ((old-index start (1+ old-index))
220        (new-index 0 (1+ new-index))
221        (copy (make-sequence-like sequence (- end start))))
222       ((= old-index end) copy)
223     (declare (fixnum old-index new-index))
224     (setf (aref copy new-index) (aref sequence old-index))))
225
226 (defun list-subseq* (sequence start &optional end)
227   (declare (type list sequence))
228   (declare (type fixnum start))
229   (declare (type (or null fixnum) end))
230   (if (and end (>= start (the fixnum end)))
231       ()
232       (let* ((groveled (nthcdr start sequence))
233              (result (list (car groveled))))
234         (if groveled
235             (do ((list (cdr groveled) (cdr list))
236                  (splice result (cdr (rplacd splice (list (car list)))))
237                  (index (1+ start) (1+ index)))
238                 ((or (atom list) (and end (= index (the fixnum end))))
239                  result)
240               (declare (fixnum index)))
241             ()))))
242
243 ;;; SUBSEQ cannot default end to the length of sequence since it is not
244 ;;; an error to supply nil for its value. We must test for end being nil
245 ;;; in the body of the function, and this is actually done in the support
246 ;;; routines for other reasons (see above).
247 (defun subseq (sequence start &optional end)
248   #!+sb-doc
249   "Return a copy of a subsequence of SEQUENCE starting with element number
250    START and continuing to the end of SEQUENCE or the optional END."
251   (seq-dispatch sequence
252                 (list-subseq* sequence start end)
253                 (vector-subseq* sequence start end)))
254 \f
255 ;;;; COPY-SEQ
256
257 (eval-when (:compile-toplevel :execute)
258
259 (sb!xc:defmacro vector-copy-seq (sequence type)
260   `(let ((length (length (the vector ,sequence))))
261      (declare (fixnum length))
262      (do ((index 0 (1+ index))
263           (copy (make-sequence-of-type ,type length)))
264          ((= index length) copy)
265        (declare (fixnum index))
266        (setf (aref copy index) (aref ,sequence index)))))
267
268 (sb!xc:defmacro list-copy-seq (list)
269   `(if (atom ,list) '()
270        (let ((result (cons (car ,list) '()) ))
271          (do ((x (cdr ,list) (cdr x))
272               (splice result
273                       (cdr (rplacd splice (cons (car x) '() ))) ))
274              ((atom x) (unless (null x)
275                                (rplacd splice x))
276                        result)))))
277
278 ) ; EVAL-WHEN
279
280 (defun copy-seq (sequence)
281   #!+sb-doc "Return a copy of SEQUENCE which is EQUAL to SEQUENCE but not EQ."
282   (seq-dispatch sequence
283                 (list-copy-seq* sequence)
284                 (vector-copy-seq* sequence)))
285
286 ;;; internal frobs
287
288 (defun list-copy-seq* (sequence)
289   (list-copy-seq sequence))
290
291 (defun vector-copy-seq* (sequence)
292   (declare (type vector sequence))
293   (vector-copy-seq sequence
294                    (typecase sequence
295                      ;; Pick off the common cases so that we don't have to... 
296                      ((vector t) 'simple-vector)
297                      (string 'simple-string)
298                      (bit-vector 'simple-bit-vector)
299                      ((vector single-float) '(simple-array single-float 1))
300                      ((vector double-float) '(simple-array double-float 1))
301                      ;; ...do a full call to TYPE-OF.
302                      (t (type-of sequence)))))
303 \f
304 ;;;; FILL
305
306 (eval-when (:compile-toplevel :execute)
307
308 (sb!xc:defmacro vector-fill (sequence item start end)
309   `(do ((index ,start (1+ index)))
310        ((= index (the fixnum ,end)) ,sequence)
311      (declare (fixnum index))
312      (setf (aref ,sequence index) ,item)))
313
314 (sb!xc:defmacro list-fill (sequence item start end)
315   `(do ((current (nthcdr ,start ,sequence) (cdr current))
316         (index ,start (1+ index)))
317        ((or (atom current) (and end (= index (the fixnum ,end))))
318         sequence)
319      (declare (fixnum index))
320      (rplaca current ,item)))
321
322 ) ; EVAL-WHEN
323
324 ;;; The support routines for FILL are used by compiler transforms, so we
325 ;;; worry about dealing with END being supplied or defaulting to NIL
326 ;;; at this level.
327
328 (defun list-fill* (sequence item start end)
329   (declare (list sequence))
330   (list-fill sequence item start end))
331
332 (defun vector-fill* (sequence item start end)
333   (declare (vector sequence))
334   (when (null end) (setq end (length sequence)))
335   (vector-fill sequence item start end))
336
337 ;;; FILL cannot default end to the length of sequence since it is not
338 ;;; an error to supply nil for its value. We must test for end being nil
339 ;;; in the body of the function, and this is actually done in the support
340 ;;; routines for other reasons (see above).
341 (defun fill (sequence item &key (start 0) end)
342   #!+sb-doc "Replace the specified elements of SEQUENCE with ITEM."
343   (seq-dispatch sequence
344                 (list-fill* sequence item start end)
345                 (vector-fill* sequence item start end)))
346 \f
347 ;;;; REPLACE
348
349 (eval-when (:compile-toplevel :execute)
350
351 ;;; If we are copying around in the same vector, be careful not to copy the
352 ;;; same elements over repeatedly. We do this by copying backwards.
353 (sb!xc:defmacro mumble-replace-from-mumble ()
354   `(if (and (eq target-sequence source-sequence) (> target-start source-start))
355        (let ((nelts (min (- target-end target-start)
356                          (- source-end source-start))))
357          (do ((target-index (+ (the fixnum target-start) (the fixnum nelts) -1)
358                             (1- target-index))
359               (source-index (+ (the fixnum source-start) (the fixnum nelts) -1)
360                             (1- source-index)))
361              ((= target-index (the fixnum (1- target-start))) target-sequence)
362            (declare (fixnum target-index source-index))
363            (setf (aref target-sequence target-index)
364                  (aref source-sequence source-index))))
365        (do ((target-index target-start (1+ target-index))
366             (source-index source-start (1+ source-index)))
367            ((or (= target-index (the fixnum target-end))
368                 (= source-index (the fixnum source-end)))
369             target-sequence)
370          (declare (fixnum target-index source-index))
371          (setf (aref target-sequence target-index)
372                (aref source-sequence source-index)))))
373
374 (sb!xc:defmacro list-replace-from-list ()
375   `(if (and (eq target-sequence source-sequence) (> target-start source-start))
376        (let ((new-elts (subseq source-sequence source-start
377                                (+ (the fixnum source-start)
378                                   (the fixnum
379                                        (min (- (the fixnum target-end)
380                                                (the fixnum target-start))
381                                             (- (the fixnum source-end)
382                                                (the fixnum source-start))))))))
383          (do ((n new-elts (cdr n))
384               (o (nthcdr target-start target-sequence) (cdr o)))
385              ((null n) target-sequence)
386            (rplaca o (car n))))
387        (do ((target-index target-start (1+ target-index))
388             (source-index source-start (1+ source-index))
389             (target-sequence-ref (nthcdr target-start target-sequence)
390                                  (cdr target-sequence-ref))
391             (source-sequence-ref (nthcdr source-start source-sequence)
392                                  (cdr source-sequence-ref)))
393            ((or (= target-index (the fixnum target-end))
394                 (= source-index (the fixnum source-end))
395                 (null target-sequence-ref) (null source-sequence-ref))
396             target-sequence)
397          (declare (fixnum target-index source-index))
398          (rplaca target-sequence-ref (car source-sequence-ref)))))
399
400 (sb!xc:defmacro list-replace-from-mumble ()
401   `(do ((target-index target-start (1+ target-index))
402         (source-index source-start (1+ source-index))
403         (target-sequence-ref (nthcdr target-start target-sequence)
404                              (cdr target-sequence-ref)))
405        ((or (= target-index (the fixnum target-end))
406             (= source-index (the fixnum source-end))
407             (null target-sequence-ref))
408         target-sequence)
409      (declare (fixnum source-index target-index))
410      (rplaca target-sequence-ref (aref source-sequence source-index))))
411
412 (sb!xc:defmacro mumble-replace-from-list ()
413   `(do ((target-index target-start (1+ target-index))
414         (source-index source-start (1+ source-index))
415         (source-sequence (nthcdr source-start source-sequence)
416                          (cdr source-sequence)))
417        ((or (= target-index (the fixnum target-end))
418             (= source-index (the fixnum source-end))
419             (null source-sequence))
420         target-sequence)
421      (declare (fixnum target-index source-index))
422      (setf (aref target-sequence target-index) (car source-sequence))))
423
424 ) ; EVAL-WHEN
425
426 ;;;; The support routines for REPLACE are used by compiler transforms, so we
427 ;;;; worry about dealing with END being supplied or defaulting to NIL
428 ;;;; at this level.
429
430 (defun list-replace-from-list* (target-sequence source-sequence target-start
431                                 target-end source-start source-end)
432   (when (null target-end) (setq target-end (length target-sequence)))
433   (when (null source-end) (setq source-end (length source-sequence)))
434   (list-replace-from-list))
435
436 (defun list-replace-from-vector* (target-sequence source-sequence target-start
437                                   target-end source-start source-end)
438   (when (null target-end) (setq target-end (length target-sequence)))
439   (when (null source-end) (setq source-end (length source-sequence)))
440   (list-replace-from-mumble))
441
442 (defun vector-replace-from-list* (target-sequence source-sequence target-start
443                                   target-end source-start source-end)
444   (when (null target-end) (setq target-end (length target-sequence)))
445   (when (null source-end) (setq source-end (length source-sequence)))
446   (mumble-replace-from-list))
447
448 (defun vector-replace-from-vector* (target-sequence source-sequence
449                                     target-start target-end source-start
450                                     source-end)
451   (when (null target-end) (setq target-end (length target-sequence)))
452   (when (null source-end) (setq source-end (length source-sequence)))
453   (mumble-replace-from-mumble))
454
455 ;;; REPLACE cannot default END arguments to the length of SEQUENCE since it
456 ;;; is not an error to supply NIL for their values. We must test for ENDs
457 ;;; being NIL in the body of the function.
458 (defun replace (target-sequence source-sequence &key
459                 ((:start1 target-start) 0)
460                 ((:end1 target-end))
461                 ((:start2 source-start) 0)
462                 ((:end2 source-end)))
463   #!+sb-doc
464   "The target sequence is destructively modified by copying successive
465    elements into it from the source sequence."
466   (let ((target-end (or target-end (length target-sequence)))
467         (source-end (or source-end (length source-sequence))))
468     (seq-dispatch target-sequence
469                   (seq-dispatch source-sequence
470                                 (list-replace-from-list)
471                                 (list-replace-from-mumble))
472                   (seq-dispatch source-sequence
473                                 (mumble-replace-from-list)
474                                 (mumble-replace-from-mumble)))))
475 \f
476 ;;;; REVERSE
477
478 (eval-when (:compile-toplevel :execute)
479
480 (sb!xc:defmacro vector-reverse (sequence type)
481   `(let ((length (length ,sequence)))
482      (declare (fixnum length))
483      (do ((forward-index 0 (1+ forward-index))
484           (backward-index (1- length) (1- backward-index))
485           (new-sequence (make-sequence-of-type ,type length)))
486          ((= forward-index length) new-sequence)
487        (declare (fixnum forward-index backward-index))
488        (setf (aref new-sequence forward-index)
489              (aref ,sequence backward-index)))))
490
491 (sb!xc:defmacro list-reverse-macro (sequence)
492   `(do ((new-list ()))
493        ((atom ,sequence) new-list)
494      (push (pop ,sequence) new-list)))
495
496 ) ; EVAL-WHEN
497
498 (defun reverse (sequence)
499   #!+sb-doc
500   "Return a new sequence containing the same elements but in reverse order."
501   (seq-dispatch sequence
502                 (list-reverse* sequence)
503                 (vector-reverse* sequence)))
504
505 ;;; internal frobs
506
507 (defun list-reverse* (sequence)
508   (list-reverse-macro sequence))
509
510 (defun vector-reverse* (sequence)
511   (vector-reverse sequence (type-of sequence)))
512 \f
513 ;;;; NREVERSE
514
515 (eval-when (:compile-toplevel :execute)
516
517 (sb!xc:defmacro vector-nreverse (sequence)
518   `(let ((length (length (the vector ,sequence))))
519      (declare (fixnum length))
520      (do ((left-index 0 (1+ left-index))
521           (right-index (1- length) (1- right-index))
522           (half-length (truncate length 2)))
523          ((= left-index half-length) ,sequence)
524        (declare (fixnum left-index right-index half-length))
525        (rotatef (aref ,sequence left-index)
526                 (aref ,sequence right-index)))))
527
528 (sb!xc:defmacro list-nreverse-macro (list)
529   `(do ((1st (cdr ,list) (if (atom 1st) 1st (cdr 1st)))
530         (2nd ,list 1st)
531         (3rd '() 2nd))
532        ((atom 2nd) 3rd)
533      (rplacd 2nd 3rd)))
534
535 ) ; EVAL-WHEN
536
537 (defun list-nreverse* (sequence)
538   (list-nreverse-macro sequence))
539
540 (defun vector-nreverse* (sequence)
541   (vector-nreverse sequence))
542
543 (defun nreverse (sequence)
544   #!+sb-doc
545   "Return a sequence of the same elements in reverse order; the argument
546    is destroyed."
547   (seq-dispatch sequence
548                 (list-nreverse* sequence)
549                 (vector-nreverse* sequence)))
550 \f
551 ;;;; CONCATENATE
552
553 (eval-when (:compile-toplevel :execute)
554
555 (sb!xc:defmacro concatenate-to-list (sequences)
556   `(let ((result (list nil)))
557      (do ((sequences ,sequences (cdr sequences))
558           (splice result))
559          ((null sequences) (cdr result))
560        (let ((sequence (car sequences)))
561          ;; FIXME: It appears to me that this and CONCATENATE-TO-MUMBLE
562          ;; could benefit from a DO-SEQUENCE macro.
563          (seq-dispatch sequence
564                        (do ((sequence sequence (cdr sequence)))
565                            ((atom sequence))
566                          (setq splice
567                                (cdr (rplacd splice (list (car sequence))))))
568                        (do ((index 0 (1+ index))
569                             (length (length sequence)))
570                            ((= index length))
571                          (declare (fixnum index length))
572                          (setq splice
573                                (cdr (rplacd splice
574                                             (list (aref sequence index)))))))))))
575
576 (sb!xc:defmacro concatenate-to-mumble (output-type-spec sequences)
577   `(do ((seqs ,sequences (cdr seqs))
578         (total-length 0)
579         (lengths ()))
580        ((null seqs)
581         (do ((sequences ,sequences (cdr sequences))
582              (lengths lengths (cdr lengths))
583              (index 0)
584              (result (make-sequence-of-type ,output-type-spec total-length)))
585             ((= index total-length) result)
586           (declare (fixnum index))
587           (let ((sequence (car sequences)))
588             (seq-dispatch sequence
589                           (do ((sequence sequence (cdr sequence)))
590                               ((atom sequence))
591                             (setf (aref result index) (car sequence))
592                             (setq index (1+ index)))
593                           (do ((jndex 0 (1+ jndex))
594                                (this-length (car lengths)))
595                               ((= jndex this-length))
596                             (declare (fixnum jndex this-length))
597                             (setf (aref result index)
598                                   (aref sequence jndex))
599                             (setq index (1+ index)))))))
600      (let ((length (length (car seqs))))
601        (declare (fixnum length))
602        (setq lengths (nconc lengths (list length)))
603        (setq total-length (+ total-length length)))))
604
605 ) ; EVAL-WHEN
606 \f
607 ;;; FIXME: Make a compiler macro or transform for this which efficiently
608 ;;; handles the case of constant 'STRING first argument. (It's not just time
609 ;;; efficiency, but space efficiency..)
610 (defun concatenate (output-type-spec &rest sequences)
611   #!+sb-doc
612   "Return a new sequence of all the argument sequences concatenated together
613   which shares no structure with the original argument sequences of the
614   specified OUTPUT-TYPE-SPEC."
615   (case (type-specifier-atom output-type-spec)
616     ((simple-vector simple-string vector string array simple-array
617                     bit-vector simple-bit-vector base-string
618                     simple-base-string) ; FIXME: unifying principle here?
619      (let ((result (apply #'concat-to-simple* output-type-spec sequences)))
620        #!+high-security (aver (typep result output-type-spec))
621        result))
622     (list (apply #'concat-to-list* sequences))
623     (t
624      (apply #'concatenate (result-type-or-lose output-type-spec) sequences))))
625
626 ;;; internal frobs
627 ;;; FIXME: These are weird. They're never called anywhere except in
628 ;;; CONCATENATE. It seems to me that the macros ought to just
629 ;;; be expanded directly in CONCATENATE, or in CONCATENATE-STRING
630 ;;; and CONCATENATE-LIST variants. Failing that, these ought to be local
631 ;;; functions (FLET).
632 (defun concat-to-list* (&rest sequences)
633   (concatenate-to-list sequences))
634 (defun concat-to-simple* (type &rest sequences)
635   (concatenate-to-mumble type sequences))
636 \f
637 ;;;; MAP and MAP-INTO
638
639 ;;; helper functions to handle arity-1 subcases of MAP
640 (declaim (ftype (function (function sequence) list) %map-list-arity-1))
641 (declaim (ftype (function (function sequence) simple-vector)
642                 %map-simple-vector-arity-1))
643 (macrolet ((dosequence ((i sequence) &body body)
644              (once-only ((sequence sequence))
645                `(etypecase ,sequence
646                   (list (dolist (,i ,sequence) ,@body))
647                   (simple-vector (dovector (,i sequence) ,@body))
648                   (vector (dovector (,i sequence) ,@body))))))
649   (defun %map-to-list-arity-1 (fun sequence)
650     (let ((reversed-result nil)
651           (really-fun (%coerce-callable-to-fun fun)))
652       (dosequence (element sequence)
653         (push (funcall really-fun element)
654               reversed-result))
655       (nreverse reversed-result)))
656   (defun %map-to-simple-vector-arity-1 (fun sequence)
657     (let ((result (make-array (length sequence)))
658           (index 0)
659           (really-fun (%coerce-callable-to-fun fun)))
660       (declare (type index index))
661       (dosequence (element sequence)
662         (setf (aref result index)
663               (funcall really-fun element))
664         (incf index))
665       result))
666   (defun %map-for-effect-arity-1 (fun sequence)
667     (let ((really-fun (%coerce-callable-to-fun fun)))
668       (dosequence (element sequence)
669         (funcall really-fun element)))
670     nil))
671
672 ;;; helper functions to handle arity-N subcases of MAP
673 ;;;
674 ;;; KLUDGE: This is hairier, and larger, than need be, because we
675 ;;; don't have DYNAMIC-EXTENT. With DYNAMIC-EXTENT, we could define
676 ;;; %MAP-FOR-EFFECT, and then implement the
677 ;;; other %MAP-TO-FOO functions reasonably efficiently by passing closures to
678 ;;; %MAP-FOR-EFFECT. (DYNAMIC-EXTENT would help a little by avoiding
679 ;;; consing each closure, and would help a lot by allowing us to define
680 ;;; a closure (LAMBDA (&REST REST) <do something with (APPLY FUN REST)>)
681 ;;; with the REST list allocated with DYNAMIC-EXTENT. -- WHN 20000920
682 (macrolet (;; Execute BODY in a context where the machinery for
683            ;; UPDATED-MAP-APPLY-ARGS has been set up.
684            (with-map-state (sequences &body body)
685              `(let* ((%sequences ,sequences)
686                      (%iters (mapcar (lambda (sequence)
687                                        (etypecase sequence
688                                          (list sequence)
689                                          (vector 0)))
690                                      %sequences))
691                      (%apply-args (make-list (length %sequences))))
692                 (declare (type list %sequences %iters %apply-args))
693                 ,@body))
694            ;; Return a list of args to pass to APPLY for the next
695            ;; function call in the mapping, or NIL if no more function
696            ;; calls should be made (because we've reached the end of a
697            ;; sequence arg).
698            (updated-map-apply-args ()
699              '(do ((in-sequences  %sequences  (cdr in-sequences))
700                    (in-iters      %iters      (cdr in-iters))
701                    (in-apply-args %apply-args (cdr in-apply-args)))
702                   ((null in-sequences)
703                    %apply-args)
704                 (declare (type list in-sequences in-iters in-apply-args))
705                 (let ((i (car in-iters)))
706                   (declare (type (or list index) i))
707                   (if (listp i)
708                       (if (null i)      ; if end of this sequence
709                           (return nil)
710                           (setf (car in-apply-args) (car i)
711                                 (car in-iters) (cdr i)))
712                       (let ((v (the vector (car in-sequences))))
713                         (if (>= i (length v)) ; if end of this sequence
714                             (return nil)
715                             (setf (car in-apply-args) (aref v i)
716                                   (car in-iters) (1+ i)))))))))
717   (defun %map-to-list (func sequences)
718     (declare (type function func))
719     (declare (type list sequences))
720     (with-map-state sequences
721       (loop with updated-map-apply-args 
722             while (setf updated-map-apply-args (updated-map-apply-args))
723             collect (apply func updated-map-apply-args))))
724   (defun %map-to-vector (output-type-spec func sequences)
725     (declare (type function func))
726     (declare (type list sequences))
727     (let ((min-len (with-map-state sequences
728                      (do ((counter 0 (1+ counter)))
729                          ;; Note: Doing everything in
730                          ;; UPDATED-MAP-APPLY-ARGS here is somewhat
731                          ;; wasteful; we even do some extra consing.
732                          ;; And stepping over every element of
733                          ;; VECTORs, instead of just grabbing their
734                          ;; LENGTH, is also wasteful. But it's easy
735                          ;; and safe. (If you do rewrite it, please
736                          ;; try to make sure that
737                          ;;   (MAP NIL #'F SOME-CIRCULAR-LIST #(1))
738                          ;; does the right thing.)
739                          ((not (updated-map-apply-args))
740                           counter)
741                        (declare (type index counter))))))
742       (declare (type index min-len))
743       (with-map-state sequences
744         (let ((result (make-sequence-of-type output-type-spec min-len))
745               (index 0))
746           (declare (type index index))
747           (loop with updated-map-apply-args
748                 while (setf updated-map-apply-args (updated-map-apply-args))
749                 do
750                 (setf (aref result index)
751                       (apply func updated-map-apply-args))
752                 (incf index))
753           result))))
754   (defun %map-for-effect (func sequences)
755     (declare (type function func))
756     (declare (type list sequences))
757     (with-map-state sequences
758       (loop with updated-map-apply-args
759             while (setf updated-map-apply-args (updated-map-apply-args))
760             do
761             (apply func updated-map-apply-args))
762       nil)))
763
764   "FUNCTION must take as many arguments as there are sequences provided.  
765   The result is a sequence of type OUTPUT-TYPE-SPEC such that element I 
766   is the result of applying FUNCTION to element I of each of the argument
767   sequences."
768
769 ;;; %MAP is just MAP without the final just-to-be-sure check that
770 ;;; length of the output sequence matches any length specified
771 ;;; in RESULT-TYPE.
772 (defun %map (result-type function first-sequence &rest more-sequences)
773   (let ((really-fun (%coerce-callable-to-fun function)))
774     ;; Handle one-argument MAP NIL specially, using ETYPECASE to turn
775     ;; it into something which can be DEFTRANSFORMed away. (It's
776     ;; fairly important to handle this case efficiently, since
777     ;; quantifiers like SOME are transformed into this case, and since
778     ;; there's no consing overhead to dwarf our inefficiency.)
779     (if (and (null more-sequences)
780              (null result-type))
781         (%map-for-effect-arity-1 really-fun first-sequence)
782         ;; Otherwise, use the industrial-strength full-generality
783         ;; approach, consing O(N-ARGS) temporary storage (which can have
784         ;; DYNAMIC-EXTENT), then using O(N-ARGS * RESULT-LENGTH) time.
785         (let ((sequences (cons first-sequence more-sequences)))
786           (case (type-specifier-atom result-type)
787             ((nil) (%map-for-effect really-fun sequences))
788             (list (%map-to-list really-fun sequences))
789             ((simple-vector simple-string vector string array simple-array
790               bit-vector simple-bit-vector base-string simple-base-string)
791              (%map-to-vector result-type really-fun sequences))
792             (t
793              (apply #'map
794                     (result-type-or-lose result-type t)
795                     really-fun
796                     sequences)))))))
797
798 (defun map (result-type function first-sequence &rest more-sequences)
799   (sequence-of-checked-length-given-type (apply #'%map
800                                                 result-type
801                                                 function
802                                                 first-sequence
803                                                 more-sequences)
804                                          ;; (The RESULT-TYPE isn't
805                                          ;; strictly the type of the
806                                          ;; result, because when
807                                          ;; RESULT-TYPE=NIL, the result
808                                          ;; actually has NULL type. But
809                                          ;; that special case doesn't
810                                          ;; matter here, since we only
811                                          ;; look closely at vector
812                                          ;; types; so we can just pass
813                                          ;; RESULT-TYPE straight through
814                                          ;; as a type specifier.)
815                                          result-type))
816
817 ;;; KLUDGE: MAP has been rewritten substantially since the fork from
818 ;;; CMU CL in order to give reasonable performance, but this
819 ;;; implementation of MAP-INTO still has the same problems as the old
820 ;;; MAP code. Ideally, MAP-INTO should be rewritten to be efficient in
821 ;;; the same way that the corresponding cases of MAP have been
822 ;;; rewritten. Instead of doing it now, though, it's easier to wait
823 ;;; until we have DYNAMIC-EXTENT, at which time it should become
824 ;;; extremely easy to define a reasonably efficient MAP-INTO in terms
825 ;;; of (MAP NIL ..). -- WHN 20000920
826 (defun map-into (result-sequence function &rest sequences)
827   (let* ((fp-result
828           (and (arrayp result-sequence)
829                (array-has-fill-pointer-p result-sequence)))
830          (len (apply #'min
831                      (if fp-result
832                          (array-dimension result-sequence 0)
833                          (length result-sequence))
834                      (mapcar #'length sequences))))
835
836     (when fp-result
837       (setf (fill-pointer result-sequence) len))
838
839     (let ((really-fun (%coerce-callable-to-fun function)))
840       (dotimes (index len)
841         (setf (elt result-sequence index)
842               (apply really-fun
843                      (mapcar (lambda (seq) (elt seq index))
844                              sequences))))))
845   result-sequence)
846 \f
847 ;;;; quantifiers
848
849 ;;; We borrow the logic from (MAP NIL ..) to handle iteration over
850 ;;; arbitrary sequence arguments, both in the full call case and in
851 ;;; the open code case.
852 (macrolet ((defquantifier (name found-test found-result
853                                 &key doc (unfound-result (not found-result)))
854              `(progn 
855                 ;; KLUDGE: It would be really nice if we could simply
856                 ;; do something like this
857                 ;;  (declaim (inline ,name))
858                 ;;  (defun ,name (pred first-seq &rest more-seqs)
859                 ;;    ,doc
860                 ;;    (flet ((map-me (&rest rest)
861                 ;;             (let ((pred-value (apply pred rest)))
862                 ;;               (,found-test pred-value
863                 ;;                 (return-from ,name
864                 ;;                   ,found-result)))))
865                 ;;      (declare (inline map-me))
866                 ;;      (apply #'map nil #'map-me first-seq more-seqs)
867                 ;;      ,unfound-result))
868                 ;; but Python doesn't seem to be smart enough about
869                 ;; inlining and APPLY to recognize that it can use
870                 ;; the DEFTRANSFORM for MAP in the resulting inline
871                 ;; expansion. I don't have any appetite for deep
872                 ;; compiler hacking right now, so I'll just work
873                 ;; around the apparent problem by using a compiler
874                 ;; macro instead. -- WHN 20000410
875                 (defun ,name (pred first-seq &rest more-seqs)
876                   #!+sb-doc ,doc
877                   (flet ((map-me (&rest rest)
878                            (let ((pred-value (apply pred rest)))
879                              (,found-test pred-value
880                                           (return-from ,name
881                                             ,found-result)))))
882                     (declare (inline map-me))
883                     (apply #'map nil #'map-me first-seq more-seqs)
884                     ,unfound-result))
885                 ;; KLUDGE: It would be more obviously correct -- but
886                 ;; also significantly messier -- for PRED-VALUE to be
887                 ;; a gensym. However, a private symbol really does
888                 ;; seem to be good enough; and anyway the really
889                 ;; obviously correct solution is to make Python smart
890                 ;; enough that we can use an inline function instead
891                 ;; of a compiler macro (as above). -- WHN 20000410
892                 ;;
893                 ;; FIXME: The DEFINE-COMPILER-MACRO here can be
894                 ;; important for performance, and it'd be good to have
895                 ;; it be visible throughout the compilation of all the
896                 ;; target SBCL code. That could be done by defining
897                 ;; SB-XC:DEFINE-COMPILER-MACRO and using it here,
898                 ;; moving this DEFQUANTIFIER stuff (and perhaps other
899                 ;; inline definitions in seq.lisp as well) into a new
900                 ;; seq.lisp, and moving remaining target-only stuff
901                 ;; from the old seq.lisp into target-seq.lisp.
902                 (define-compiler-macro ,name (pred first-seq &rest more-seqs)
903                   (let ((elements (make-gensym-list (1+ (length more-seqs))))
904                         (blockname (gensym "BLOCK")))
905                     (once-only ((pred pred))
906                       `(block ,blockname
907                          (map nil
908                               (lambda (,@elements)
909                                 (let ((pred-value (funcall ,pred ,@elements)))
910                                   (,',found-test pred-value
911                                     (return-from ,blockname
912                                       ,',found-result))))
913                               ,first-seq
914                               ,@more-seqs)
915                          ,',unfound-result)))))))
916   (defquantifier some when pred-value :unfound-result nil :doc
917   "Apply PREDICATE to the 0-indexed elements of the sequences, then 
918    possibly to those with index 1, and so on. Return the first 
919    non-NIL value encountered, or NIL if the end of any sequence is reached.")
920   (defquantifier every unless nil :doc
921   "Apply PREDICATE to the 0-indexed elements of the sequences, then
922    possibly to those with index 1, and so on. Return NIL as soon
923    as any invocation of PREDICATE returns NIL, or T if every invocation
924    is non-NIL.")
925   (defquantifier notany when nil :doc
926   "Apply PREDICATE to the 0-indexed elements of the sequences, then 
927    possibly to those with index 1, and so on. Return NIL as soon
928    as any invocation of PREDICATE returns a non-NIL value, or T if the end
929    of any sequence is reached.")
930   (defquantifier notevery unless t :doc
931   "Apply PREDICATE to 0-indexed elements of the sequences, then
932    possibly to those with index 1, and so on. Return T as soon
933    as any invocation of PREDICATE returns NIL, or NIL if every invocation
934    is non-NIL."))
935 \f
936 ;;;; REDUCE
937
938 (eval-when (:compile-toplevel :execute)
939
940 (sb!xc:defmacro mumble-reduce (function
941                                sequence
942                                key
943                                start
944                                end
945                                initial-value
946                                ref)
947   `(do ((index ,start (1+ index))
948         (value ,initial-value))
949        ((= index (the fixnum ,end)) value)
950      (declare (fixnum index))
951      (setq value (funcall ,function value
952                           (apply-key ,key (,ref ,sequence index))))))
953
954 (sb!xc:defmacro mumble-reduce-from-end (function
955                                         sequence
956                                         key
957                                         start
958                                         end
959                                         initial-value
960                                         ref)
961   `(do ((index (1- ,end) (1- index))
962         (value ,initial-value)
963         (terminus (1- ,start)))
964        ((= index terminus) value)
965      (declare (fixnum index terminus))
966      (setq value (funcall ,function
967                           (apply-key ,key (,ref ,sequence index))
968                           value))))
969
970 (sb!xc:defmacro list-reduce (function
971                              sequence
972                              key
973                              start
974                              end
975                              initial-value
976                              ivp)
977   `(let ((sequence (nthcdr ,start ,sequence)))
978      (do ((count (if ,ivp ,start (1+ (the fixnum ,start)))
979                  (1+ count))
980           (sequence (if ,ivp sequence (cdr sequence))
981                     (cdr sequence))
982           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
983                  (funcall ,function value (apply-key ,key (car sequence)))))
984          ((= count (the fixnum ,end)) value)
985        (declare (fixnum count)))))
986
987 (sb!xc:defmacro list-reduce-from-end (function
988                                       sequence
989                                       key
990                                       start
991                                       end
992                                       initial-value
993                                       ivp)
994   `(let ((sequence (nthcdr (- (the fixnum (length ,sequence))
995                               (the fixnum ,end))
996                            (reverse ,sequence))))
997      (do ((count (if ,ivp ,start (1+ (the fixnum ,start)))
998                  (1+ count))
999           (sequence (if ,ivp sequence (cdr sequence))
1000                     (cdr sequence))
1001           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1002                  (funcall ,function (apply-key ,key (car sequence)) value)))
1003          ((= count (the fixnum ,end)) value)
1004        (declare (fixnum count)))))
1005
1006 ) ; EVAL-WHEN
1007
1008 (defun reduce (function sequence &key key from-end (start 0)
1009                         end (initial-value nil ivp))
1010   (declare (type index start))
1011   (let ((start start)
1012         (end (or end (length sequence))))
1013     (declare (type index start end))
1014     (cond ((= end start)
1015            (if ivp initial-value (funcall function)))
1016           ((listp sequence)
1017            (if from-end
1018                (list-reduce-from-end function sequence key start end
1019                                      initial-value ivp)
1020                (list-reduce function sequence key start end
1021                             initial-value ivp)))
1022           (from-end
1023            (when (not ivp)
1024              (setq end (1- (the fixnum end)))
1025              (setq initial-value (apply-key key (aref sequence end))))
1026            (mumble-reduce-from-end function sequence key start end
1027                                    initial-value aref))
1028           (t
1029            (when (not ivp)
1030              (setq initial-value (apply-key key (aref sequence start)))
1031              (setq start (1+ start)))
1032            (mumble-reduce function sequence key start end
1033                           initial-value aref)))))
1034 \f
1035 ;;;; DELETE
1036
1037 (eval-when (:compile-toplevel :execute)
1038
1039 (sb!xc:defmacro mumble-delete (pred)
1040   `(do ((index start (1+ index))
1041         (jndex start)
1042         (number-zapped 0))
1043        ((or (= index (the fixnum end)) (= number-zapped (the fixnum count)))
1044         (do ((index index (1+ index))           ; Copy the rest of the vector.
1045              (jndex jndex (1+ jndex)))
1046             ((= index (the fixnum length))
1047              (shrink-vector sequence jndex))
1048           (declare (fixnum index jndex))
1049           (setf (aref sequence jndex) (aref sequence index))))
1050      (declare (fixnum index jndex number-zapped))
1051      (setf (aref sequence jndex) (aref sequence index))
1052      (if ,pred
1053          (setq number-zapped (1+ number-zapped))
1054          (setq jndex (1+ jndex)))))
1055
1056 (sb!xc:defmacro mumble-delete-from-end (pred)
1057   `(do ((index (1- (the fixnum end)) (1- index)) ; Find the losers.
1058         (number-zapped 0)
1059         (losers ())
1060         this-element
1061         (terminus (1- start)))
1062        ((or (= index terminus) (= number-zapped (the fixnum count)))
1063         (do ((losers losers)                     ; Delete the losers.
1064              (index start (1+ index))
1065              (jndex start))
1066             ((or (null losers) (= index (the fixnum end)))
1067              (do ((index index (1+ index))       ; Copy the rest of the vector.
1068                   (jndex jndex (1+ jndex)))
1069                  ((= index (the fixnum length))
1070                   (shrink-vector sequence jndex))
1071                (declare (fixnum index jndex))
1072                (setf (aref sequence jndex) (aref sequence index))))
1073           (declare (fixnum index jndex))
1074           (setf (aref sequence jndex) (aref sequence index))
1075           (if (= index (the fixnum (car losers)))
1076               (pop losers)
1077               (setq jndex (1+ jndex)))))
1078      (declare (fixnum index number-zapped terminus))
1079      (setq this-element (aref sequence index))
1080      (when ,pred
1081        (setq number-zapped (1+ number-zapped))
1082        (push index losers))))
1083
1084 (sb!xc:defmacro normal-mumble-delete ()
1085   `(mumble-delete
1086     (if test-not
1087         (not (funcall test-not item (apply-key key (aref sequence index))))
1088         (funcall test item (apply-key key (aref sequence index))))))
1089
1090 (sb!xc:defmacro normal-mumble-delete-from-end ()
1091   `(mumble-delete-from-end
1092     (if test-not
1093         (not (funcall test-not item (apply-key key this-element)))
1094         (funcall test item (apply-key key this-element)))))
1095
1096 (sb!xc:defmacro list-delete (pred)
1097   `(let ((handle (cons nil sequence)))
1098      (do ((current (nthcdr start sequence) (cdr current))
1099           (previous (nthcdr start handle))
1100           (index start (1+ index))
1101           (number-zapped 0))
1102          ((or (= index (the fixnum end)) (= number-zapped (the fixnum count)))
1103           (cdr handle))
1104        (declare (fixnum index number-zapped))
1105        (cond (,pred
1106               (rplacd previous (cdr current))
1107               (setq number-zapped (1+ number-zapped)))
1108              (t
1109               (setq previous (cdr previous)))))))
1110
1111 (sb!xc:defmacro list-delete-from-end (pred)
1112   `(let* ((reverse (nreverse (the list sequence)))
1113           (handle (cons nil reverse)))
1114      (do ((current (nthcdr (- (the fixnum length) (the fixnum end)) reverse)
1115                    (cdr current))
1116           (previous (nthcdr (- (the fixnum length) (the fixnum end)) handle))
1117           (index start (1+ index))
1118           (number-zapped 0))
1119          ((or (= index (the fixnum end)) (= number-zapped (the fixnum count)))
1120           (nreverse (cdr handle)))
1121        (declare (fixnum index number-zapped))
1122        (cond (,pred
1123               (rplacd previous (cdr current))
1124               (setq number-zapped (1+ number-zapped)))
1125              (t
1126               (setq previous (cdr previous)))))))
1127
1128 (sb!xc:defmacro normal-list-delete ()
1129   '(list-delete
1130     (if test-not
1131         (not (funcall test-not item (apply-key key (car current))))
1132         (funcall test item (apply-key key (car current))))))
1133
1134 (sb!xc:defmacro normal-list-delete-from-end ()
1135   '(list-delete-from-end
1136     (if test-not
1137         (not (funcall test-not item (apply-key key (car current))))
1138         (funcall test item (apply-key key (car current))))))
1139
1140 ) ; EVAL-WHEN
1141
1142 (defun delete (item sequence &key from-end (test #'eql) test-not (start 0)
1143                 end count key)
1144   #!+sb-doc
1145   "Return a sequence formed by destructively removing the specified ITEM from
1146   the given SEQUENCE."
1147   (declare (fixnum start))
1148   (let* ((length (length sequence))
1149          (end (or end length))
1150          (count (or count most-positive-fixnum)))
1151     (declare (type index length end)
1152              (fixnum count))
1153     (seq-dispatch sequence
1154                   (if from-end
1155                       (normal-list-delete-from-end)
1156                       (normal-list-delete))
1157                   (if from-end
1158                       (normal-mumble-delete-from-end)
1159                       (normal-mumble-delete)))))
1160
1161 (eval-when (:compile-toplevel :execute)
1162
1163 (sb!xc:defmacro if-mumble-delete ()
1164   `(mumble-delete
1165     (funcall predicate (apply-key key (aref sequence index)))))
1166
1167 (sb!xc:defmacro if-mumble-delete-from-end ()
1168   `(mumble-delete-from-end
1169     (funcall predicate (apply-key key this-element))))
1170
1171 (sb!xc:defmacro if-list-delete ()
1172   '(list-delete
1173     (funcall predicate (apply-key key (car current)))))
1174
1175 (sb!xc:defmacro if-list-delete-from-end ()
1176   '(list-delete-from-end
1177     (funcall predicate (apply-key key (car current)))))
1178
1179 ) ; EVAL-WHEN
1180
1181 (defun delete-if (predicate sequence &key from-end (start 0) key end count)
1182   #!+sb-doc
1183   "Return a sequence formed by destructively removing the elements satisfying
1184   the specified PREDICATE from the given SEQUENCE."
1185   (declare (fixnum start))
1186   (let* ((length (length sequence))
1187          (end (or end length))
1188          (count (or count most-positive-fixnum)))
1189     (declare (type index length end)
1190              (fixnum count))
1191     (seq-dispatch sequence
1192                   (if from-end
1193                       (if-list-delete-from-end)
1194                       (if-list-delete))
1195                   (if from-end
1196                       (if-mumble-delete-from-end)
1197                       (if-mumble-delete)))))
1198
1199 (eval-when (:compile-toplevel :execute)
1200
1201 (sb!xc:defmacro if-not-mumble-delete ()
1202   `(mumble-delete
1203     (not (funcall predicate (apply-key key (aref sequence index))))))
1204
1205 (sb!xc:defmacro if-not-mumble-delete-from-end ()
1206   `(mumble-delete-from-end
1207     (not (funcall predicate (apply-key key this-element)))))
1208
1209 (sb!xc:defmacro if-not-list-delete ()
1210   '(list-delete
1211     (not (funcall predicate (apply-key key (car current))))))
1212
1213 (sb!xc:defmacro if-not-list-delete-from-end ()
1214   '(list-delete-from-end
1215     (not (funcall predicate (apply-key key (car current))))))
1216
1217 ) ; EVAL-WHEN
1218
1219 (defun delete-if-not (predicate sequence &key from-end (start 0) end key count)
1220   #!+sb-doc
1221   "Return a sequence formed by destructively removing the elements not
1222   satisfying the specified PREDICATE from the given SEQUENCE."
1223   (declare (fixnum start))
1224   (let* ((length (length sequence))
1225          (end (or end length))
1226          (count (or count most-positive-fixnum)))
1227     (declare (type index length end)
1228              (fixnum count))
1229     (seq-dispatch sequence
1230                   (if from-end
1231                       (if-not-list-delete-from-end)
1232                       (if-not-list-delete))
1233                   (if from-end
1234                       (if-not-mumble-delete-from-end)
1235                       (if-not-mumble-delete)))))
1236 \f
1237 ;;;; REMOVE
1238
1239 (eval-when (:compile-toplevel :execute)
1240
1241 ;;; MUMBLE-REMOVE-MACRO does not include (removes) each element that
1242 ;;; satisfies the predicate.
1243 (sb!xc:defmacro mumble-remove-macro (bump left begin finish right pred)
1244   `(do ((index ,begin (,bump index))
1245         (result
1246          (do ((index ,left (,bump index))
1247               (result (make-sequence-like sequence length)))
1248              ((= index (the fixnum ,begin)) result)
1249            (declare (fixnum index))
1250            (setf (aref result index) (aref sequence index))))
1251         (new-index ,begin)
1252         (number-zapped 0)
1253         (this-element))
1254        ((or (= index (the fixnum ,finish))
1255             (= number-zapped (the fixnum count)))
1256         (do ((index index (,bump index))
1257              (new-index new-index (,bump new-index)))
1258             ((= index (the fixnum ,right)) (shrink-vector result new-index))
1259           (declare (fixnum index new-index))
1260           (setf (aref result new-index) (aref sequence index))))
1261      (declare (fixnum index new-index number-zapped))
1262      (setq this-element (aref sequence index))
1263      (cond (,pred (setq number-zapped (1+ number-zapped)))
1264            (t (setf (aref result new-index) this-element)
1265               (setq new-index (,bump new-index))))))
1266
1267 (sb!xc:defmacro mumble-remove (pred)
1268   `(mumble-remove-macro 1+ 0 start end length ,pred))
1269
1270 (sb!xc:defmacro mumble-remove-from-end (pred)
1271   `(let ((sequence (copy-seq sequence)))
1272      (mumble-delete-from-end ,pred)))
1273
1274 (sb!xc:defmacro normal-mumble-remove ()
1275   `(mumble-remove
1276     (if test-not
1277         (not (funcall test-not item (apply-key key this-element)))
1278         (funcall test item (apply-key key this-element)))))
1279
1280 (sb!xc:defmacro normal-mumble-remove-from-end ()
1281   `(mumble-remove-from-end
1282     (if test-not
1283         (not (funcall test-not item (apply-key key this-element)))
1284         (funcall test item (apply-key key this-element)))))
1285
1286 (sb!xc:defmacro if-mumble-remove ()
1287   `(mumble-remove (funcall predicate (apply-key key this-element))))
1288
1289 (sb!xc:defmacro if-mumble-remove-from-end ()
1290   `(mumble-remove-from-end (funcall predicate (apply-key key this-element))))
1291
1292 (sb!xc:defmacro if-not-mumble-remove ()
1293   `(mumble-remove (not (funcall predicate (apply-key key this-element)))))
1294
1295 (sb!xc:defmacro if-not-mumble-remove-from-end ()
1296   `(mumble-remove-from-end
1297     (not (funcall predicate (apply-key key this-element)))))
1298
1299 ;;; LIST-REMOVE-MACRO does not include (removes) each element that satisfies
1300 ;;; the predicate.
1301 (sb!xc:defmacro list-remove-macro (pred reverse?)
1302   `(let* ((sequence ,(if reverse?
1303                          '(reverse (the list sequence))
1304                          'sequence))
1305           (splice (list nil))
1306           (results (do ((index 0 (1+ index))
1307                         (before-start splice))
1308                        ((= index (the fixnum start)) before-start)
1309                      (declare (fixnum index))
1310                      (setq splice
1311                            (cdr (rplacd splice (list (pop sequence))))))))
1312      (do ((index start (1+ index))
1313           (this-element)
1314           (number-zapped 0))
1315          ((or (= index (the fixnum end)) (= number-zapped (the fixnum count)))
1316           (do ((index index (1+ index)))
1317               ((null sequence)
1318                ,(if reverse?
1319                     '(nreverse (the list (cdr results)))
1320                     '(cdr results)))
1321             (declare (fixnum index))
1322             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1323        (declare (fixnum index number-zapped))
1324        (setq this-element (pop sequence))
1325        (if ,pred
1326            (setq number-zapped (1+ number-zapped))
1327            (setq splice (cdr (rplacd splice (list this-element))))))))
1328
1329 (sb!xc:defmacro list-remove (pred)
1330   `(list-remove-macro ,pred nil))
1331
1332 (sb!xc:defmacro list-remove-from-end (pred)
1333   `(list-remove-macro ,pred t))
1334
1335 (sb!xc:defmacro normal-list-remove ()
1336   `(list-remove
1337     (if test-not
1338         (not (funcall test-not item (apply-key key this-element)))
1339         (funcall test item (apply-key key this-element)))))
1340
1341 (sb!xc:defmacro normal-list-remove-from-end ()
1342   `(list-remove-from-end
1343     (if test-not
1344         (not (funcall test-not item (apply-key key this-element)))
1345         (funcall test item (apply-key key this-element)))))
1346
1347 (sb!xc:defmacro if-list-remove ()
1348   `(list-remove
1349     (funcall predicate (apply-key key this-element))))
1350
1351 (sb!xc:defmacro if-list-remove-from-end ()
1352   `(list-remove-from-end
1353     (funcall predicate (apply-key key this-element))))
1354
1355 (sb!xc:defmacro if-not-list-remove ()
1356   `(list-remove
1357     (not (funcall predicate (apply-key key this-element)))))
1358
1359 (sb!xc:defmacro if-not-list-remove-from-end ()
1360   `(list-remove-from-end
1361     (not (funcall predicate (apply-key key this-element)))))
1362
1363 ) ; EVAL-WHEN
1364
1365 (defun remove (item sequence &key from-end (test #'eql) test-not (start 0)
1366                 end count key)
1367   #!+sb-doc
1368   "Return a copy of SEQUENCE with elements satisfying the test (default is
1369    EQL) with ITEM removed."
1370   (declare (fixnum start))
1371   (let* ((length (length sequence))
1372          (end (or end length))
1373          (count (or count most-positive-fixnum)))
1374     (declare (type index length end)
1375              (fixnum count))
1376     (seq-dispatch sequence
1377                   (if from-end
1378                       (normal-list-remove-from-end)
1379                       (normal-list-remove))
1380                   (if from-end
1381                       (normal-mumble-remove-from-end)
1382                       (normal-mumble-remove)))))
1383
1384 (defun remove-if (predicate sequence &key from-end (start 0) end count key)
1385   #!+sb-doc
1386   "Return a copy of sequence with elements such that predicate(element)
1387    is non-null removed"
1388   (declare (fixnum start))
1389   (let* ((length (length sequence))
1390          (end (or end length))
1391          (count (or count most-positive-fixnum)))
1392     (declare (type index length end)
1393              (fixnum count))
1394     (seq-dispatch sequence
1395                   (if from-end
1396                       (if-list-remove-from-end)
1397                       (if-list-remove))
1398                   (if from-end
1399                       (if-mumble-remove-from-end)
1400                       (if-mumble-remove)))))
1401
1402 (defun remove-if-not (predicate sequence &key from-end (start 0) end count key)
1403   #!+sb-doc
1404   "Return a copy of sequence with elements such that predicate(element)
1405    is null removed"
1406   (declare (fixnum start))
1407   (let* ((length (length sequence))
1408          (end (or end length))
1409          (count (or count most-positive-fixnum)))
1410     (declare (type index length end)
1411              (fixnum count))
1412     (seq-dispatch sequence
1413                   (if from-end
1414                       (if-not-list-remove-from-end)
1415                       (if-not-list-remove))
1416                   (if from-end
1417                       (if-not-mumble-remove-from-end)
1418                       (if-not-mumble-remove)))))
1419 \f
1420 ;;;; REMOVE-DUPLICATES
1421
1422 ;;; Remove duplicates from a list. If from-end, remove the later duplicates,
1423 ;;; not the earlier ones. Thus if we check from-end we don't copy an item
1424 ;;; if we look into the already copied structure (from after :start) and see
1425 ;;; the item. If we check from beginning we check into the rest of the
1426 ;;; original list up to the :end marker (this we have to do by running a
1427 ;;; do loop down the list that far and using our test.
1428 (defun list-remove-duplicates* (list test test-not start end key from-end)
1429   (declare (fixnum start))
1430   (let* ((result (list ())) ; Put a marker on the beginning to splice with.
1431          (splice result)
1432          (current list))
1433     (do ((index 0 (1+ index)))
1434         ((= index start))
1435       (declare (fixnum index))
1436       (setq splice (cdr (rplacd splice (list (car current)))))
1437       (setq current (cdr current)))
1438     (do ((index 0 (1+ index)))
1439         ((or (and end (= index (the fixnum end)))
1440              (atom current)))
1441       (declare (fixnum index))
1442       (if (or (and from-end
1443                    (not (member (apply-key key (car current))
1444                                 (nthcdr (1+ start) result)
1445                                 :test test
1446                                 :test-not test-not
1447                                 :key key)))
1448               (and (not from-end)
1449                    (not (do ((it (apply-key key (car current)))
1450                              (l (cdr current) (cdr l))
1451                              (i (1+ index) (1+ i)))
1452                             ((or (atom l) (and end (= i (the fixnum end))))
1453                              ())
1454                           (declare (fixnum i))
1455                           (if (if test-not
1456                                   (not (funcall test-not it (apply-key key (car l))))
1457                                   (funcall test it (apply-key key (car l))))
1458                               (return t))))))
1459           (setq splice (cdr (rplacd splice (list (car current))))))
1460       (setq current (cdr current)))
1461     (do ()
1462         ((atom current))
1463       (setq splice (cdr (rplacd splice (list (car current)))))
1464       (setq current (cdr current)))
1465     (cdr result)))
1466
1467 (defun vector-remove-duplicates* (vector test test-not start end key from-end
1468                                          &optional (length (length vector)))
1469   (declare (vector vector) (fixnum start length))
1470   (when (null end) (setf end (length vector)))
1471   (let ((result (make-sequence-like vector length))
1472         (index 0)
1473         (jndex start))
1474     (declare (fixnum index jndex))
1475     (do ()
1476         ((= index start))
1477       (setf (aref result index) (aref vector index))
1478       (setq index (1+ index)))
1479     (do ((elt))
1480         ((= index end))
1481       (setq elt (aref vector index))
1482       (unless (or (and from-end
1483                         (position (apply-key key elt) result :start start
1484                            :end jndex :test test :test-not test-not :key key))
1485                   (and (not from-end)
1486                         (position (apply-key key elt) vector :start (1+ index)
1487                            :end end :test test :test-not test-not :key key)))
1488         (setf (aref result jndex) elt)
1489         (setq jndex (1+ jndex)))
1490       (setq index (1+ index)))
1491     (do ()
1492         ((= index length))
1493       (setf (aref result jndex) (aref vector index))
1494       (setq index (1+ index))
1495       (setq jndex (1+ jndex)))
1496     (shrink-vector result jndex)))
1497
1498 (defun remove-duplicates (sequence &key
1499                                    (test #'eql)
1500                                    test-not
1501                                    (start 0)
1502                                    from-end
1503                                    end
1504                                    key)
1505   #!+sb-doc
1506   "The elements of Sequence are compared pairwise, and if any two match,
1507    the one occurring earlier is discarded, unless FROM-END is true, in
1508    which case the one later in the sequence is discarded. The resulting
1509    sequence is returned.
1510
1511    The :TEST-NOT argument is depreciated."
1512   (declare (fixnum start))
1513   (seq-dispatch sequence
1514                 (if sequence
1515                     (list-remove-duplicates* sequence test test-not
1516                                               start end key from-end))
1517                 (vector-remove-duplicates* sequence test test-not
1518                                             start end key from-end)))
1519 \f
1520 ;;;; DELETE-DUPLICATES
1521
1522 (defun list-delete-duplicates* (list test test-not key from-end start end)
1523   (declare (fixnum start))
1524   (let ((handle (cons nil list)))
1525     (do ((current (nthcdr start list) (cdr current))
1526          (previous (nthcdr start handle))
1527          (index start (1+ index)))
1528         ((or (and end (= index (the fixnum end))) (null current))
1529          (cdr handle))
1530       (declare (fixnum index))
1531       (if (do ((x (if from-end
1532                       (nthcdr (1+ start) handle)
1533                       (cdr current))
1534                   (cdr x))
1535                (i (1+ index) (1+ i)))
1536               ((or (null x)
1537                    (and (not from-end) end (= i (the fixnum end)))
1538                    (eq x current))
1539                nil)
1540             (declare (fixnum i))
1541             (if (if test-not
1542                     (not (funcall test-not
1543                                   (apply-key key (car current))
1544                                   (apply-key key (car x))))
1545                     (funcall test
1546                              (apply-key key (car current))
1547                              (apply-key key (car x))))
1548                 (return t)))
1549           (rplacd previous (cdr current))
1550           (setq previous (cdr previous))))))
1551
1552 (defun vector-delete-duplicates* (vector test test-not key from-end start end
1553                                          &optional (length (length vector)))
1554   (declare (vector vector) (fixnum start length))
1555   (when (null end) (setf end (length vector)))
1556   (do ((index start (1+ index))
1557        (jndex start))
1558       ((= index end)
1559        (do ((index index (1+ index))            ; copy the rest of the vector
1560             (jndex jndex (1+ jndex)))
1561            ((= index length)
1562             (shrink-vector vector jndex)
1563             vector)
1564          (setf (aref vector jndex) (aref vector index))))
1565     (declare (fixnum index jndex))
1566     (setf (aref vector jndex) (aref vector index))
1567     (unless (position (apply-key key (aref vector index)) vector :key key
1568                       :start (if from-end start (1+ index)) :test test
1569                       :end (if from-end jndex end) :test-not test-not)
1570       (setq jndex (1+ jndex)))))
1571
1572 (defun delete-duplicates (sequence &key
1573                                    (test #'eql)
1574                                    test-not
1575                                    (start 0)
1576                                    from-end
1577                                    end
1578                                    key)
1579   #!+sb-doc
1580   "The elements of Sequence are examined, and if any two match, one is
1581    discarded. The resulting sequence, which may be formed by destroying the
1582    given sequence, is returned.
1583
1584    The :TEST-NOT argument is depreciated."
1585   (seq-dispatch sequence
1586     (if sequence
1587         (list-delete-duplicates* sequence test test-not key from-end start end))
1588   (vector-delete-duplicates* sequence test test-not key from-end start end)))
1589 \f
1590 ;;;; SUBSTITUTE
1591
1592 (defun list-substitute* (pred new list start end count key test test-not old)
1593   (declare (fixnum start end count))
1594   (let* ((result (list nil))
1595          elt
1596          (splice result)
1597          (list list))      ; Get a local list for a stepper.
1598     (do ((index 0 (1+ index)))
1599         ((= index start))
1600       (declare (fixnum index))
1601       (setq splice (cdr (rplacd splice (list (car list)))))
1602       (setq list (cdr list)))
1603     (do ((index start (1+ index)))
1604         ((or (= index end) (null list) (= count 0)))
1605       (declare (fixnum index))
1606       (setq elt (car list))
1607       (setq splice
1608             (cdr (rplacd splice
1609                          (list
1610                           (cond
1611                            ((case pred
1612                                    (normal
1613                                     (if test-not
1614                                         (not
1615                                          (funcall test-not old (apply-key key elt)))
1616                                         (funcall test old (apply-key key elt))))
1617                                    (if (funcall test (apply-key key elt)))
1618                                    (if-not (not (funcall test (apply-key key elt)))))
1619                             (setq count (1- count))
1620                             new)
1621                                 (t elt))))))
1622       (setq list (cdr list)))
1623     (do ()
1624         ((null list))
1625       (setq splice (cdr (rplacd splice (list (car list)))))
1626       (setq list (cdr list)))
1627     (cdr result)))
1628
1629 ;;; Replace old with new in sequence moving from left to right by incrementer
1630 ;;; on each pass through the loop. Called by all three substitute functions.
1631 (defun vector-substitute* (pred new sequence incrementer left right length
1632                            start end count key test test-not old)
1633   (declare (fixnum start count end incrementer right))
1634   (let ((result (make-sequence-like sequence length))
1635         (index left))
1636     (declare (fixnum index))
1637     (do ()
1638         ((= index start))
1639       (setf (aref result index) (aref sequence index))
1640       (setq index (+ index incrementer)))
1641     (do ((elt))
1642         ((or (= index end) (= count 0)))
1643       (setq elt (aref sequence index))
1644       (setf (aref result index)
1645             (cond ((case pred
1646                           (normal
1647                             (if test-not
1648                                 (not (funcall test-not old (apply-key key elt)))
1649                                 (funcall test old (apply-key key elt))))
1650                           (if (funcall test (apply-key key elt)))
1651                           (if-not (not (funcall test (apply-key key elt)))))
1652                    (setq count (1- count))
1653                    new)
1654                   (t elt)))
1655       (setq index (+ index incrementer)))
1656     (do ()
1657         ((= index right))
1658       (setf (aref result index) (aref sequence index))
1659       (setq index (+ index incrementer)))
1660     result))
1661
1662 (eval-when (:compile-toplevel :execute)
1663
1664 (sb!xc:defmacro subst-dispatch (pred)
1665   `(if (listp sequence)
1666        (if from-end
1667            (nreverse (list-substitute* ,pred
1668                                        new
1669                                        (reverse sequence)
1670                                        (- (the fixnum length)
1671                                           (the fixnum end))
1672                                        (- (the fixnum length)
1673                                           (the fixnum start))
1674                                        count key test test-not old))
1675            (list-substitute* ,pred
1676                              new sequence start end count key test test-not
1677                              old))
1678       (if from-end
1679           (vector-substitute* ,pred new sequence -1 (1- (the fixnum length))
1680                               -1 length (1- (the fixnum end))
1681                               (1- (the fixnum start))
1682                               count key test test-not old)
1683           (vector-substitute* ,pred new sequence 1 0 length length
1684            start end count key test test-not old))))
1685
1686 ) ; EVAL-WHEN
1687
1688 (defun substitute (new old sequence &key from-end (test #'eql) test-not
1689                    (start 0) count end key)
1690   #!+sb-doc
1691   "Return a sequence of the same kind as SEQUENCE with the same elements,
1692   except that all elements equal to OLD are replaced with NEW. See manual
1693   for details."
1694   (declare (fixnum start))
1695   (let* ((length (length sequence))
1696          (end (or end length))
1697          (count (or count most-positive-fixnum)))
1698     (declare (type index length end)
1699              (fixnum count))
1700     (subst-dispatch 'normal)))
1701 \f
1702 ;;;; SUBSTITUTE-IF, SUBSTITUTE-IF-NOT
1703
1704 (defun substitute-if (new test sequence &key from-end (start 0) end count key)
1705   #!+sb-doc
1706   "Return a sequence of the same kind as SEQUENCE with the same elements
1707   except that all elements satisfying the TEST are replaced with NEW. See
1708   manual for details."
1709   (declare (fixnum start))
1710   (let* ((length (length sequence))
1711          (end (or end length))
1712          (count (or count most-positive-fixnum))
1713          test-not
1714          old)
1715     (declare (type index length end)
1716              (fixnum count))
1717     (subst-dispatch 'if)))
1718
1719 (defun substitute-if-not (new test sequence &key from-end (start 0)
1720                            end count key)
1721   #!+sb-doc
1722   "Return a sequence of the same kind as SEQUENCE with the same elements
1723   except that all elements not satisfying the TEST are replaced with NEW.
1724   See manual for details."
1725   (declare (fixnum start))
1726   (let* ((length (length sequence))
1727          (end (or end length))
1728          (count (or count most-positive-fixnum))
1729          test-not
1730          old)
1731     (declare (type index length end)
1732              (fixnum count))
1733     (subst-dispatch 'if-not)))
1734 \f
1735 ;;;; NSUBSTITUTE
1736
1737 (defun nsubstitute (new old sequence &key from-end (test #'eql) test-not
1738                      end count key (start 0))
1739   #!+sb-doc
1740   "Return a sequence of the same kind as SEQUENCE with the same elements
1741   except that all elements equal to OLD are replaced with NEW. The SEQUENCE
1742   may be destructively modified. See manual for details."
1743   (declare (fixnum start))
1744   (let ((end (or end (length sequence)))
1745         (count (or count most-positive-fixnum)))
1746     (declare (fixnum count))
1747     (if (listp sequence)
1748         (if from-end
1749             (nreverse (nlist-substitute*
1750                        new old (nreverse (the list sequence))
1751                        test test-not start end count key))
1752             (nlist-substitute* new old sequence
1753                                test test-not start end count key))
1754         (if from-end
1755             (nvector-substitute* new old sequence -1
1756                                  test test-not (1- end) (1- start) count key)
1757             (nvector-substitute* new old sequence 1
1758                                  test test-not start end count key)))))
1759
1760 (defun nlist-substitute* (new old sequence test test-not start end count key)
1761   (declare (fixnum start count end))
1762   (do ((list (nthcdr start sequence) (cdr list))
1763        (index start (1+ index)))
1764       ((or (= index end) (null list) (= count 0)) sequence)
1765     (declare (fixnum index))
1766     (when (if test-not
1767               (not (funcall test-not old (apply-key key (car list))))
1768               (funcall test old (apply-key key (car list))))
1769       (rplaca list new)
1770       (setq count (1- count)))))
1771
1772 (defun nvector-substitute* (new old sequence incrementer
1773                             test test-not start end count key)
1774   (declare (fixnum start incrementer count end))
1775   (do ((index start (+ index incrementer)))
1776       ((or (= index end) (= count 0)) sequence)
1777     (declare (fixnum index))
1778     (when (if test-not
1779               (not (funcall test-not
1780                             old
1781                             (apply-key key (aref sequence index))))
1782               (funcall test old (apply-key key (aref sequence index))))
1783       (setf (aref sequence index) new)
1784       (setq count (1- count)))))
1785 \f
1786 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
1787
1788 (defun nsubstitute-if (new test sequence &key from-end (start 0) end count key)
1789   #!+sb-doc
1790   "Return a sequence of the same kind as SEQUENCE with the same elements
1791    except that all elements satisfying the TEST are replaced with NEW. 
1792    SEQUENCE may be destructively modified. See manual for details."
1793   (declare (fixnum start))
1794   (let ((end (or end (length sequence)))
1795         (count (or count most-positive-fixnum)))
1796     (declare (fixnum end count))
1797     (if (listp sequence)
1798         (if from-end
1799             (nreverse (nlist-substitute-if*
1800                        new test (nreverse (the list sequence))
1801                        start end count key))
1802             (nlist-substitute-if* new test sequence
1803                                   start end count key))
1804         (if from-end
1805             (nvector-substitute-if* new test sequence -1
1806                                     (1- end) (1- start) count key)
1807             (nvector-substitute-if* new test sequence 1
1808                                     start end count key)))))
1809
1810 (defun nlist-substitute-if* (new test sequence start end count key)
1811   (declare (fixnum end))
1812   (do ((list (nthcdr start sequence) (cdr list))
1813        (index start (1+ index)))
1814       ((or (= index end) (null list) (= count 0)) sequence)
1815     (when (funcall test (apply-key key (car list)))
1816       (rplaca list new)
1817       (setq count (1- count)))))
1818
1819 (defun nvector-substitute-if* (new test sequence incrementer
1820                                start end count key)
1821   (do ((index start (+ index incrementer)))
1822       ((or (= index end) (= count 0)) sequence)
1823     (when (funcall test (apply-key key (aref sequence index)))
1824       (setf (aref sequence index) new)
1825       (setq count (1- count)))))
1826
1827 (defun nsubstitute-if-not (new test sequence &key from-end (start 0)
1828                                end count key)
1829   #!+sb-doc
1830   "Return a sequence of the same kind as SEQUENCE with the same elements
1831    except that all elements not satisfying the TEST are replaced with NEW.
1832    SEQUENCE may be destructively modified. See manual for details."
1833   (declare (fixnum start))
1834   (let ((end (or end (length sequence)))
1835         (count (or count most-positive-fixnum)))
1836     (declare (fixnum end count))
1837     (if (listp sequence)
1838         (if from-end
1839             (nreverse (nlist-substitute-if-not*
1840                        new test (nreverse (the list sequence))
1841                        start end count key))
1842             (nlist-substitute-if-not* new test sequence
1843                                       start end count key))
1844         (if from-end
1845             (nvector-substitute-if-not* new test sequence -1
1846                                         (1- end) (1- start) count key)
1847             (nvector-substitute-if-not* new test sequence 1
1848                                         start end count key)))))
1849
1850 (defun nlist-substitute-if-not* (new test sequence start end count key)
1851   (declare (fixnum end))
1852   (do ((list (nthcdr start sequence) (cdr list))
1853        (index start (1+ index)))
1854       ((or (= index end) (null list) (= count 0)) sequence)
1855     (when (not (funcall test (apply-key key (car list))))
1856       (rplaca list new)
1857       (setq count (1- count)))))
1858
1859 (defun nvector-substitute-if-not* (new test sequence incrementer
1860                                    start end count key)
1861   (do ((index start (+ index incrementer)))
1862       ((or (= index end) (= count 0)) sequence)
1863     (when (not (funcall test (apply-key key (aref sequence index))))
1864       (setf (aref sequence index) new)
1865       (setq count (1- count)))))
1866 \f
1867 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
1868
1869 ;;; logic to unravel :TEST, :TEST-NOT, and :KEY options in FIND,
1870 ;;; POSITION-IF, etc.
1871 (declaim (inline effective-find-position-test effective-find-position-key))
1872 (defun effective-find-position-test (test test-not)
1873   (cond ((and test test-not)
1874          (error "can't specify both :TEST and :TEST-NOT"))
1875         (test (%coerce-callable-to-fun test))
1876         (test-not
1877          ;; (Without DYNAMIC-EXTENT, this is potentially horribly
1878          ;; inefficient, but since the TEST-NOT option is deprecated
1879          ;; anyway, we don't care.)
1880          (complement (%coerce-callable-to-fun test-not)))
1881         (t #'eql)))
1882 (defun effective-find-position-key (key)
1883   (if key
1884       (%coerce-callable-to-fun key)
1885       #'identity))
1886
1887 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
1888 (macrolet (;; shared logic for defining %FIND-POSITION and
1889            ;; %FIND-POSITION-IF in terms of various inlineable cases
1890            ;; of the expression defined in FROB and VECTOR*-FROB
1891            (frobs ()
1892              `(etypecase sequence-arg
1893                 (list (frob sequence-arg from-end))
1894                 (vector 
1895                  (with-array-data ((sequence sequence-arg :offset-var offset)
1896                                    (start start)
1897                                    (end (or end (length sequence-arg))))
1898                    (multiple-value-bind (f p)
1899                        (macrolet ((frob2 () '(if from-end
1900                                                  (frob sequence t)
1901                                                  (frob sequence nil))))
1902                          (typecase sequence
1903                            (simple-vector (frob2))
1904                            (simple-string (frob2))
1905                            (t (vector*-frob sequence))))
1906                      (declare (type (or index null) p))
1907                      (values f (and p (the index (+ p offset))))))))))
1908   (defun %find-position (item sequence-arg from-end start end key test)
1909     (macrolet ((frob (sequence from-end)
1910                  `(%find-position item ,sequence
1911                                   ,from-end start end key test))
1912                (vector*-frob (sequence)
1913                  `(%find-position-vector-macro item ,sequence
1914                                                from-end start end key test)))
1915       (frobs)))
1916   (defun %find-position-if (predicate sequence-arg from-end start end key)
1917     (macrolet ((frob (sequence from-end)
1918                  `(%find-position-if predicate ,sequence
1919                                      ,from-end start end key))
1920                (vector*-frob (sequence)
1921                  `(%find-position-if-vector-macro predicate ,sequence
1922                                                   from-end start end key)))
1923       (frobs)))
1924   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
1925     (macrolet ((frob (sequence from-end)
1926                  `(%find-position-if-not predicate ,sequence
1927                                          ,from-end start end key))
1928                (vector*-frob (sequence)
1929                  `(%find-position-if-not-vector-macro predicate ,sequence
1930                                                   from-end start end key)))
1931       (frobs))))
1932
1933 ;;; the user interface to FIND and POSITION: Get all our ducks in a
1934 ;;; row, then call %FIND-POSITION.
1935 (declaim (inline find position))
1936 (macrolet ((def-find-position (fun-name values-index)
1937              `(defun ,fun-name (item
1938                                 sequence
1939                                 &key
1940                                 from-end
1941                                 (start 0)
1942                                 end
1943                                 key
1944                                 test
1945                                 test-not)
1946                 (nth-value
1947                  ,values-index
1948                  (%find-position item
1949                                  sequence
1950                                  from-end
1951                                  start
1952                                  end
1953                                  (effective-find-position-key key)
1954                                  (effective-find-position-test test
1955                                                                test-not))))))
1956   (def-find-position find 0)
1957   (def-find-position position 1))
1958
1959 ;;; the user interface to FIND-IF and POSITION-IF, entirely analogous
1960 ;;; to the interface to FIND and POSITION
1961 (declaim (inline find-if position-if))
1962 (macrolet ((def-find-position-if (fun-name values-index)
1963              `(defun ,fun-name (predicate sequence
1964                                 &key from-end (start 0) end key)
1965                 (nth-value
1966                  ,values-index
1967                  (%find-position-if (%coerce-callable-to-fun predicate)
1968                                     sequence
1969                                     from-end
1970                                     start
1971                                     end
1972                                     (effective-find-position-key key))))))
1973   
1974   (def-find-position-if find-if 0)
1975   (def-find-position-if position-if 1))
1976
1977 ;;; the deprecated functions FIND-IF-NOT and POSITION-IF-NOT. We
1978 ;;; didn't bother to worry about optimizing them, except note that on
1979 ;;; Sat, Oct 06, 2001 at 04:22:38PM +0100, Christophe Rhodes wrote on
1980 ;;; sbcl-devel
1981 ;;;
1982 ;;;     My understanding is that while the :test-not argument is
1983 ;;;     deprecated in favour of :test (complement #'foo) because of
1984 ;;;     semantic difficulties (what happens if both :test and :test-not
1985 ;;;     are supplied, etc) the -if-not variants, while officially
1986 ;;;     deprecated, would be undeprecated were X3J13 actually to produce
1987 ;;;     a revised standard, as there are perfectly legitimate idiomatic
1988 ;;;     reasons for allowing the -if-not versions equal status,
1989 ;;;     particularly remove-if-not (== filter).
1990 ;;;   
1991 ;;;     This is only an informal understanding, I grant you, but
1992 ;;;     perhaps it's worth optimizing the -if-not versions in the same
1993 ;;;     way as the others?
1994 ;;;
1995 ;;; That sounds reasonable, so if someone wants to submit patches to
1996 ;;; make the -IF-NOT functions compile as efficiently as the
1997 ;;; corresponding -IF variants do, go for it. -- WHN 2001-10-06)
1998 ;;;
1999 ;;; FIXME: Remove uses of these deprecated functions (and of :TEST-NOT
2000 ;;; too) within the implementation of SBCL.
2001 (declaim (inline find-if-not position-if-not))
2002 (macrolet ((def-find-position-if-not (fun-name values-index)
2003              `(defun ,fun-name (predicate sequence
2004                                 &key from-end (start 0) end key)
2005                 (nth-value
2006                  ,values-index
2007                  (%find-position-if-not (%coerce-callable-to-fun predicate)
2008                                         sequence
2009                                         from-end
2010                                         start
2011                                         end
2012                                         (effective-find-position-key key))))))
2013   
2014   (def-find-position-if-not find-if-not 0)
2015   (def-find-position-if-not position-if-not 1))
2016 \f
2017 ;;;; COUNT
2018
2019 (eval-when (:compile-toplevel :execute)
2020
2021 (sb!xc:defmacro vector-count (item sequence)
2022   `(do ((index start (1+ index))
2023         (count 0))
2024        ((= index (the fixnum end)) count)
2025      (declare (fixnum index count))
2026      (if test-not
2027          (unless (funcall test-not ,item
2028                           (apply-key key (aref ,sequence index)))
2029            (setq count (1+ count)))
2030          (when (funcall test ,item (apply-key key (aref ,sequence index)))
2031            (setq count (1+ count))))))
2032
2033 (sb!xc:defmacro list-count (item sequence)
2034   `(do ((sequence (nthcdr start ,sequence))
2035         (index start (1+ index))
2036         (count 0))
2037        ((or (= index (the fixnum end)) (null sequence)) count)
2038      (declare (fixnum index count))
2039      (if test-not
2040          (unless (funcall test-not ,item (apply-key key (pop sequence)))
2041            (setq count (1+ count)))
2042          (when (funcall test ,item (apply-key key (pop sequence)))
2043            (setq count (1+ count))))))
2044
2045 ) ; EVAL-WHEN
2046
2047 (defun count (item sequence &key from-end (test #'eql) test-not (start 0)
2048                 end key)
2049   #!+sb-doc
2050   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2051    which defaults to EQL."
2052   (declare (ignore from-end) (fixnum start))
2053   (let ((end (or end (length sequence))))
2054     (declare (type index end))
2055     (seq-dispatch sequence
2056                   (list-count item sequence)
2057                   (vector-count item sequence))))
2058 \f
2059 ;;;; COUNT-IF and COUNT-IF-NOT
2060
2061 (eval-when (:compile-toplevel :execute)
2062
2063 (sb!xc:defmacro vector-count-if (predicate sequence)
2064   `(do ((index start (1+ index))
2065         (count 0))
2066        ((= index (the fixnum end)) count)
2067      (declare (fixnum index count))
2068      (if (funcall ,predicate (apply-key key (aref ,sequence index)))
2069          (setq count (1+ count)))))
2070
2071 (sb!xc:defmacro list-count-if (predicate sequence)
2072   `(do ((sequence (nthcdr start ,sequence))
2073         (index start (1+ index))
2074         (count 0))
2075        ((or (= index (the fixnum end)) (null sequence)) count)
2076      (declare (fixnum index count))
2077      (if (funcall ,predicate (apply-key key (pop sequence)))
2078          (setq count (1+ count)))))
2079
2080 ) ; EVAL-WHEN
2081
2082 (defun count-if (test sequence &key from-end (start 0) end key)
2083   #!+sb-doc
2084   "Return the number of elements in SEQUENCE satisfying TEST(el)."
2085   (declare (ignore from-end) (fixnum start))
2086   (let ((end (or end (length sequence))))
2087     (declare (type index end))
2088     (seq-dispatch sequence
2089                   (list-count-if test sequence)
2090                   (vector-count-if test sequence))))
2091
2092 (eval-when (:compile-toplevel :execute)
2093
2094 (sb!xc:defmacro vector-count-if-not (predicate sequence)
2095   `(do ((index start (1+ index))
2096         (count 0))
2097        ((= index (the fixnum end)) count)
2098      (declare (fixnum index count))
2099      (if (not (funcall ,predicate (apply-key key (aref ,sequence index))))
2100          (setq count (1+ count)))))
2101
2102 (sb!xc:defmacro list-count-if-not (predicate sequence)
2103   `(do ((sequence (nthcdr start ,sequence))
2104         (index start (1+ index))
2105         (count 0))
2106        ((or (= index (the fixnum end)) (null sequence)) count)
2107      (declare (fixnum index count))
2108      (if (not (funcall ,predicate (apply-key key (pop sequence))))
2109          (setq count (1+ count)))))
2110
2111 ) ; EVAL-WHEN
2112
2113 (defun count-if-not (test sequence &key from-end (start 0) end key)
2114   #!+sb-doc
2115   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2116   (declare (ignore from-end) (fixnum start))
2117   (let ((end (or end (length sequence))))
2118     (declare (type index end))
2119     (seq-dispatch sequence
2120                   (list-count-if-not test sequence)
2121                   (vector-count-if-not test sequence))))
2122 \f
2123 ;;;; MISMATCH
2124
2125 (eval-when (:compile-toplevel :execute)
2126
2127 (sb!xc:defmacro match-vars (&rest body)
2128   `(let ((inc (if from-end -1 1))
2129          (start1 (if from-end (1- (the fixnum end1)) start1))
2130          (start2 (if from-end (1- (the fixnum end2)) start2))
2131          (end1 (if from-end (1- (the fixnum start1)) end1))
2132          (end2 (if from-end (1- (the fixnum start2)) end2)))
2133      (declare (fixnum inc start1 start2 end1 end2))
2134      ,@body))
2135
2136 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2137   (declare (ignore end)) ;; ### Should END be used below?
2138   `(let ((,sequence (if from-end
2139                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2140                                 (reverse (the list ,sequence)))
2141                         (nthcdr ,start ,sequence))))
2142      (declare (type list ,sequence))
2143      ,@body))
2144
2145 ) ; EVAL-WHEN
2146
2147 (eval-when (:compile-toplevel :execute)
2148
2149 (sb!xc:defmacro if-mismatch (elt1 elt2)
2150   `(cond ((= (the fixnum index1) (the fixnum end1))
2151           (return (if (= (the fixnum index2) (the fixnum end2))
2152                       nil
2153                       (if from-end
2154                           (1+ (the fixnum index1))
2155                           (the fixnum index1)))))
2156          ((= (the fixnum index2) (the fixnum end2))
2157           (return (if from-end (1+ (the fixnum index1)) index1)))
2158          (test-not
2159           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2160               (return (if from-end (1+ (the fixnum index1)) index1))))
2161          (t (if (not (funcall test (apply-key key ,elt1)
2162                               (apply-key key ,elt2)))
2163                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2164
2165 (sb!xc:defmacro mumble-mumble-mismatch ()
2166   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2167         (index2 start2 (+ index2 (the fixnum inc))))
2168        (())
2169      (declare (fixnum index1 index2))
2170      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2171
2172 (sb!xc:defmacro mumble-list-mismatch ()
2173   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2174         (index2 start2 (+ index2 (the fixnum inc))))
2175        (())
2176      (declare (fixnum index1 index2))
2177      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2178 \f
2179 (sb!xc:defmacro list-mumble-mismatch ()
2180   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2181         (index2 start2 (+ index2 (the fixnum inc))))
2182        (())
2183      (declare (fixnum index1 index2))
2184      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2185
2186 (sb!xc:defmacro list-list-mismatch ()
2187   `(do ((sequence1 sequence1)
2188         (sequence2 sequence2)
2189         (index1 start1 (+ index1 (the fixnum inc)))
2190         (index2 start2 (+ index2 (the fixnum inc))))
2191        (())
2192      (declare (fixnum index1 index2))
2193      (if-mismatch (pop sequence1) (pop sequence2))))
2194
2195 ) ; EVAL-WHEN
2196
2197 (defun mismatch (sequence1 sequence2 &key from-end (test #'eql) test-not
2198                            (start1 0) end1 (start2 0) end2 key)
2199   #!+sb-doc
2200   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2201    element-wise. If they are of equal length and match in every element, the
2202    result is Nil. Otherwise, the result is a non-negative integer, the index
2203    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2204    if one is shorter than and a matching prefix of the other, the index within
2205    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2206    :FROM-END argument is given, then one plus the index of the rightmost
2207    position in which the sequences differ is returned."
2208   (declare (fixnum start1 start2))
2209   (let* ((length1 (length sequence1))
2210          (end1 (or end1 length1))
2211          (length2 (length sequence2))
2212          (end2 (or end2 length2)))
2213     (declare (type index length1 end1 length2 end2))
2214     (match-vars
2215      (seq-dispatch sequence1
2216        (matchify-list (sequence1 start1 length1 end1)
2217          (seq-dispatch sequence2
2218            (matchify-list (sequence2 start2 length2 end2)
2219              (list-list-mismatch))
2220            (list-mumble-mismatch)))
2221        (seq-dispatch sequence2
2222          (matchify-list (sequence2 start2 length2 end2)
2223            (mumble-list-mismatch))
2224          (mumble-mumble-mismatch))))))
2225 \f
2226 ;;; search comparison functions
2227
2228 (eval-when (:compile-toplevel :execute)
2229
2230 ;;; Compare two elements and return if they don't match.
2231 (sb!xc:defmacro compare-elements (elt1 elt2)
2232   `(if test-not
2233        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2234            (return nil)
2235            t)
2236        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2237            (return nil)
2238            t)))
2239
2240 (sb!xc:defmacro search-compare-list-list (main sub)
2241   `(do ((main ,main (cdr main))
2242         (jndex start1 (1+ jndex))
2243         (sub (nthcdr start1 ,sub) (cdr sub)))
2244        ((or (null main) (null sub) (= (the fixnum end1) jndex))
2245         t)
2246      (declare (fixnum jndex))
2247      (compare-elements (car main) (car sub))))
2248
2249 (sb!xc:defmacro search-compare-list-vector (main sub)
2250   `(do ((main ,main (cdr main))
2251         (index start1 (1+ index)))
2252        ((or (null main) (= index (the fixnum end1))) t)
2253      (declare (fixnum index))
2254      (compare-elements (car main) (aref ,sub index))))
2255
2256 (sb!xc:defmacro search-compare-vector-list (main sub index)
2257   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2258         (jndex start1 (1+ jndex))
2259         (index ,index (1+ index)))
2260        ((or (= (the fixnum end1) jndex) (null sub)) t)
2261      (declare (fixnum jndex index))
2262      (compare-elements (aref ,main index) (car sub))))
2263
2264 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2265   `(do ((index ,index (1+ index))
2266         (sub-index start1 (1+ sub-index)))
2267        ((= sub-index (the fixnum end1)) t)
2268      (declare (fixnum sub-index index))
2269      (compare-elements (aref ,main index) (aref ,sub sub-index))))
2270
2271 (sb!xc:defmacro search-compare (main-type main sub index)
2272   (if (eq main-type 'list)
2273       `(seq-dispatch ,sub
2274                      (search-compare-list-list ,main ,sub)
2275                      (search-compare-list-vector ,main ,sub))
2276       `(seq-dispatch ,sub
2277                      (search-compare-vector-list ,main ,sub ,index)
2278                      (search-compare-vector-vector ,main ,sub ,index))))
2279
2280 ) ; EVAL-WHEN
2281 \f
2282 ;;;; SEARCH
2283
2284 (eval-when (:compile-toplevel :execute)
2285
2286 (sb!xc:defmacro list-search (main sub)
2287   `(do ((main (nthcdr start2 ,main) (cdr main))
2288         (index2 start2 (1+ index2))
2289         (terminus (- (the fixnum end2)
2290                      (the fixnum (- (the fixnum end1)
2291                                     (the fixnum start1)))))
2292         (last-match ()))
2293        ((> index2 terminus) last-match)
2294      (declare (fixnum index2 terminus))
2295      (if (search-compare list main ,sub index2)
2296          (if from-end
2297              (setq last-match index2)
2298              (return index2)))))
2299
2300 (sb!xc:defmacro vector-search (main sub)
2301   `(do ((index2 start2 (1+ index2))
2302         (terminus (- (the fixnum end2)
2303                      (the fixnum (- (the fixnum end1)
2304                                     (the fixnum start1)))))
2305         (last-match ()))
2306        ((> index2 terminus) last-match)
2307      (declare (fixnum index2 terminus))
2308      (if (search-compare vector ,main ,sub index2)
2309          (if from-end
2310              (setq last-match index2)
2311              (return index2)))))
2312
2313 ) ; EVAL-WHEN
2314
2315 (defun search (sequence1 sequence2 &key from-end (test #'eql) test-not
2316                 (start1 0) end1 (start2 0) end2 key)
2317   (declare (fixnum start1 start2))
2318   (let ((end1 (or end1 (length sequence1)))
2319         (end2 (or end2 (length sequence2))))
2320     (seq-dispatch sequence2
2321                   (list-search sequence2 sequence1)
2322                   (vector-search sequence2 sequence1))))