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