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