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