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