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