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