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