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