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