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