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