0.8.0.78.vector-nil-string.8:
[sbcl.git] / src / code / seq.lisp
1 ;;;; generic SEQUENCEs
2 ;;;;
3 ;;;; KLUDGE: comment from original CMU CL source:
4 ;;;;   Be careful when modifying code. A lot of the structure of the
5 ;;;;   code is affected by the fact that compiler transforms use the
6 ;;;;   lower level support functions. If transforms are written for
7 ;;;;   some sequence operation, note how the END argument is handled
8 ;;;;   in other operations with transforms.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!IMPL")
20 \f
21 ;;;; utilities
22
23 (eval-when (:compile-toplevel)
24
25 (defparameter *sequence-keyword-info*
26   ;; (name default supplied-p adjustment new-type)
27   `((count nil
28            nil
29            (etypecase count
30              (null (1- most-positive-fixnum))
31              (fixnum (max 0 count))
32              (integer (if (minusp count)
33                           0
34                           (1- most-positive-fixnum))))
35            (mod #.sb!xc:most-positive-fixnum))
36     ,@(mapcan (lambda (names)
37                 (destructuring-bind (start end length sequence) names
38                   (list
39                    `(,start
40                      0
41                      nil
42                      (if (<= 0 ,start ,length)
43                          ,start
44                          (signal-bounding-indices-bad-error ,sequence
45                                                             ,start ,end))
46                      index)
47                   `(,end
48                     nil
49                     nil
50                     (if (or (null ,end) (<= ,start ,end ,length))
51                         ;; Defaulting of NIL is done inside the
52                         ;; bodies, for ease of sharing with compiler
53                         ;; transforms.
54                         ;;
55                         ;; FIXME: defend against non-number non-NIL
56                         ;; stuff?
57                         ,end
58                         (signal-bounding-indices-bad-error ,sequence
59                                                            ,start ,end))
60                     (or null index)))))
61               '((start end length sequence)
62                 (start1 end1 length1 sequence1)
63                 (start2 end2 length2 sequence2)))
64     ))
65
66 (sb!xc:defmacro define-sequence-traverser (name args &body body)
67   (multiple-value-bind (body declarations docstring)
68       (parse-body body t)
69     (collect ((new-args) (new-declarations) (adjustments))
70       (dolist (arg args)
71         (case arg
72           ;; FIXME: make this robust.  And clean.
73           ((sequence)
74            (new-args arg)
75            (adjustments '(length (etypecase sequence
76                                    (list (length sequence))
77                                    (vector (length sequence)))))
78            (new-declarations '(type index length)))
79           ((sequence1)
80            (new-args arg)
81            (adjustments '(length1 (etypecase sequence1
82                                     (list (length sequence1))
83                                     (vector (length sequence1)))))
84            (new-declarations '(type index length1)))
85           ((sequence2)
86            (new-args arg)
87            (adjustments '(length2 (etypecase sequence2
88                                     (list (length sequence2))
89                                     (vector (length sequence2)))))
90            (new-declarations '(type index length2)))
91           (t (let ((info (cdr (assoc arg *sequence-keyword-info*))))
92                (cond (info
93                       (destructuring-bind (default supplied-p adjuster type) info
94                         (new-args `(,arg ,default ,@(when supplied-p (list supplied-p))))
95                         (adjustments `(,arg ,adjuster))
96                         (new-declarations `(type ,type ,arg))))
97                      (t (new-args arg)))))))
98       `(defun ,name ,(new-args)
99          ,@(when docstring (list docstring))
100          ,@declarations
101          (let* (,@(adjustments))
102            (declare ,@(new-declarations))
103            ,@body)))))
104
105 ;;; SEQ-DISPATCH does an efficient type-dispatch on the given SEQUENCE.
106 ;;;
107 ;;; FIXME: It might be worth making three cases here, LIST,
108 ;;; SIMPLE-VECTOR, and VECTOR, instead of the current LIST and VECTOR.
109 ;;; It tends to make code run faster but be bigger; some benchmarking
110 ;;; is needed to decide.
111 (sb!xc:defmacro seq-dispatch (sequence list-form array-form)
112   `(if (listp ,sequence)
113        ,list-form
114        ,array-form))
115
116 (sb!xc:defmacro make-sequence-like (sequence length)
117   #!+sb-doc
118   "Return a sequence of the same type as SEQUENCE and the given LENGTH."
119   `(if (typep ,sequence 'list)
120        (make-list ,length)
121        (progn
122          ;; This is only called from places which have already deduced
123          ;; that the SEQUENCE argument is actually a sequence.  So
124          ;; this would be a candidate place for (AVER (TYPEP ,SEQUENCE
125          ;; 'VECTOR)), except that this seems to be a performance
126          ;; hotspot.
127          (make-array ,length
128                      :element-type (array-element-type ,sequence)))))
129
130 (sb!xc:defmacro bad-sequence-type-error (type-spec)
131   `(error 'simple-type-error
132           :datum ,type-spec
133           ;; FIXME: This is actually wrong, and should be something
134           ;; like (SATISFIES IS-A-VALID-SEQUENCE-TYPE-SPECIFIER-P).
135           :expected-type 'sequence
136           :format-control "~S is a bad type specifier for sequences."
137           :format-arguments (list ,type-spec)))
138
139 (sb!xc:defmacro sequence-type-length-mismatch-error (type length)
140   `(error 'simple-type-error
141           :datum ,length
142           :expected-type (cond ((array-type-p ,type)
143                                 `(eql ,(car (array-type-dimensions ,type))))
144                                ((type= ,type (specifier-type 'null))
145                                 '(eql 0))
146                                ((cons-type-p ,type)
147                                 '(integer 1))
148                                (t (bug "weird type in S-T-L-M-ERROR")))
149           ;; FIXME: this format control causes ugly printing.  There's
150           ;; probably some ~<~@:_~> incantation that would make it
151           ;; nicer. -- CSR, 2002-10-18
152           :format-control "The length requested (~S) does not match the type restriction in ~S."
153           :format-arguments (list ,length (type-specifier ,type))))
154
155 (sb!xc:defmacro sequence-type-too-hairy (type-spec)
156   ;; FIXME: Should this be a BUG? I'm inclined to think not; there are
157   ;; words that give some but not total support to this position in
158   ;; ANSI.  Essentially, we are justified in throwing this on
159   ;; e.g. '(OR SIMPLE-VECTOR (VECTOR FIXNUM)), but maybe not (by ANSI)
160   ;; on '(CONS * (CONS * NULL)) -- CSR, 2002-10-18
161   `(error 'simple-type-error
162           :datum ,type-spec
163           ;; FIXME: as in BAD-SEQUENCE-TYPE-ERROR, this is wrong.
164           :expected-type 'sequence
165           :format-control "~S is too hairy for sequence functions."
166           :format-arguments (list ,type-spec)))
167 ) ; EVAL-WHEN
168
169 ;;; It's possible with some sequence operations to declare the length
170 ;;; of a result vector, and to be safe, we really ought to verify that
171 ;;; the actual result has the declared length.
172 (defun vector-of-checked-length-given-length (vector declared-length)
173   (declare (type vector vector))
174   (declare (type index declared-length))
175   (let ((actual-length (length vector)))
176     (unless (= actual-length declared-length)
177       (error 'simple-type-error
178              :datum vector
179              :expected-type `(vector ,declared-length)
180              :format-control
181              "Vector length (~W) doesn't match declared length (~W)."
182              :format-arguments (list actual-length declared-length))))
183   vector)
184 (defun sequence-of-checked-length-given-type (sequence result-type)
185   (let ((ctype (specifier-type result-type)))
186     (if (not (array-type-p ctype))
187         sequence
188         (let ((declared-length (first (array-type-dimensions ctype))))
189           (if (eq declared-length '*)
190               sequence
191               (vector-of-checked-length-given-length sequence
192                                                      declared-length))))))
193
194 (declaim (ftype (function (sequence index) nil) signal-index-too-large-error))
195 (defun signal-index-too-large-error (sequence index)
196   (let* ((length (length sequence))
197          (max-index (and (plusp length)
198                          (1- length))))
199     (error 'index-too-large-error
200            :datum index
201            :expected-type (if max-index
202                               `(integer 0 ,max-index)
203                               ;; This seems silly, is there something better?
204                               '(integer 0 (0))))))
205
206 (defun signal-bounding-indices-bad-error (sequence start end)
207   (let ((length (length sequence)))
208     (error 'bounding-indices-bad-error
209            :datum (cons start end)
210            :expected-type `(cons (integer 0 ,length)
211                                  (or null (integer ,start ,length)))
212            :object sequence)))
213 \f
214 (defun elt (sequence index)
215   #!+sb-doc "Return the element of SEQUENCE specified by INDEX."
216   (etypecase sequence
217     (list
218      (do ((count index (1- count))
219           (list sequence (cdr list)))
220          ((= count 0)
221           (if (endp list)
222               (signal-index-too-large-error sequence index)
223               (car list)))
224        (declare (type (integer 0) count))))
225     (vector
226      (when (>= index (length sequence))
227        (signal-index-too-large-error sequence index))
228      (aref sequence index))))
229
230 (defun %setelt (sequence index newval)
231   #!+sb-doc "Store NEWVAL as the component of SEQUENCE specified by INDEX."
232   (etypecase sequence
233     (list
234      (do ((count index (1- count))
235           (seq sequence))
236          ((= count 0) (rplaca seq newval) newval)
237        (declare (fixnum count))
238        (if (atom (cdr seq))
239            (signal-index-too-large-error sequence index)
240            (setq seq (cdr seq)))))
241     (vector
242      (when (>= index (length sequence))
243        (signal-index-too-large-error sequence index))
244      (setf (aref sequence index) newval))))
245
246 (defun length (sequence)
247   #!+sb-doc "Return an integer that is the length of SEQUENCE."
248   (etypecase sequence
249     (vector (length (truly-the vector sequence)))
250     (list (length (truly-the list sequence)))))
251
252 (defun make-sequence (type length &key (initial-element nil iep))
253   #!+sb-doc
254   "Return a sequence of the given TYPE and LENGTH, with elements initialized
255   to :INITIAL-ELEMENT."
256   (declare (fixnum length))
257   (let* ((adjusted-type
258           (typecase type
259             (atom (cond
260                     ((eq type 'string) '(vector character))
261                     ((eq type 'simple-string) '(simple-array character (*)))
262                     (t type)))
263             (cons (cond
264                     ((eq (car type) 'string) `(vector character ,@(cdr type)))
265                     ((eq (car type) 'simple-string)
266                      `(simple-array character ,@(when (cdr type)
267                                                       (list (cdr type)))))
268                     (t type)))
269             (t type)))
270          (type (specifier-type adjusted-type)))
271     (cond ((csubtypep type (specifier-type 'list))
272            (cond
273              ((type= type (specifier-type 'list))
274               (make-list length :initial-element initial-element))
275              ((eq type *empty-type*)
276               (bad-sequence-type-error nil))
277              ((type= type (specifier-type 'null))
278               (if (= length 0)
279                   'nil
280                   (sequence-type-length-mismatch-error type length)))
281              ((csubtypep (specifier-type '(cons nil t)) type)
282               ;; The above is quite a neat way of finding out if
283               ;; there's a type restriction on the CDR of the
284               ;; CONS... if there is, I think it's probably fair to
285               ;; give up; if there isn't, then the list to be made
286               ;; must have a length of more than 0.
287               (if (> length 0)
288                   (make-list length :initial-element initial-element)
289                   (sequence-type-length-mismatch-error type length)))
290              ;; We'll get here for e.g. (OR NULL (CONS INTEGER *)),
291              ;; which may seem strange and non-ideal, but then I'd say
292              ;; it was stranger to feed that type in to MAKE-SEQUENCE.
293              (t (sequence-type-too-hairy (type-specifier type)))))
294           ((csubtypep type (specifier-type 'vector))
295            (cond
296              (;; is it immediately obvious what the result type is?
297               (typep type 'array-type)
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              (t (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      (declare (fixnum length))
622      (do ((left-index 0 (1+ left-index))
623           (right-index (1- length) (1- right-index))
624           (half-length (truncate length 2)))
625          ((= left-index half-length) ,sequence)
626        (declare (fixnum left-index right-index half-length))
627        (rotatef (aref ,sequence left-index)
628                 (aref ,sequence right-index)))))
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 #'eql) 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 #'eql) 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 #'eql) test-not (start 0) 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 #'eql) test-not (start 0) 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 #'eql) 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 test sequence &key from-end start end count key)
1804   #!+sb-doc
1805   "Return a sequence of the same kind as SEQUENCE with the same elements
1806   except that all elements satisfying the TEST are replaced with NEW. See
1807   manual for details."
1808   (declare (fixnum start))
1809   (let ((end (or end length))
1810         test-not
1811         old)
1812     (declare (type index length end))
1813     (subst-dispatch 'if)))
1814
1815 (define-sequence-traverser substitute-if-not
1816     (new test sequence &key from-end start end count key)
1817   #!+sb-doc
1818   "Return a sequence of the same kind as SEQUENCE with the same elements
1819   except that all elements not satisfying the TEST are replaced with NEW.
1820   See manual for details."
1821   (declare (fixnum start))
1822   (let ((end (or end length))
1823         test-not
1824         old)
1825     (declare (type index length end))
1826     (subst-dispatch 'if-not)))
1827 \f
1828 ;;;; NSUBSTITUTE
1829
1830 (define-sequence-traverser nsubstitute
1831     (new old sequence &key from-end (test #'eql) test-not
1832          end count key start)
1833   #!+sb-doc
1834   "Return a sequence of the same kind as SEQUENCE with the same elements
1835   except that all elements equal to OLD are replaced with NEW. The SEQUENCE
1836   may be destructively modified. See manual for details."
1837   (declare (fixnum start))
1838   (let ((end (or end length)))
1839     (if (listp sequence)
1840         (if from-end
1841             (let ((length (length sequence)))
1842               (nreverse (nlist-substitute*
1843                          new old (nreverse (the list sequence))
1844                          test test-not (- length end) (- length start)
1845                          count key)))
1846             (nlist-substitute* new old sequence
1847                                test test-not start end count key))
1848         (if from-end
1849             (nvector-substitute* new old sequence -1
1850                                  test test-not (1- end) (1- start) count key)
1851             (nvector-substitute* new old sequence 1
1852                                  test test-not start end count key)))))
1853
1854 (defun nlist-substitute* (new old sequence test test-not start end count key)
1855   (declare (fixnum start count end))
1856   (do ((list (nthcdr start sequence) (cdr list))
1857        (index start (1+ index)))
1858       ((or (= index end) (null list) (= count 0)) sequence)
1859     (declare (fixnum index))
1860     (when (if test-not
1861               (not (funcall test-not old (apply-key key (car list))))
1862               (funcall test old (apply-key key (car list))))
1863       (rplaca list new)
1864       (setq count (1- count)))))
1865
1866 (defun nvector-substitute* (new old sequence incrementer
1867                             test test-not start end count key)
1868   (declare (fixnum start incrementer count end))
1869   (do ((index start (+ index incrementer)))
1870       ((or (= index end) (= count 0)) sequence)
1871     (declare (fixnum index))
1872     (when (if test-not
1873               (not (funcall test-not
1874                             old
1875                             (apply-key key (aref sequence index))))
1876               (funcall test old (apply-key key (aref sequence index))))
1877       (setf (aref sequence index) new)
1878       (setq count (1- count)))))
1879 \f
1880 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
1881
1882 (define-sequence-traverser nsubstitute-if
1883     (new test sequence &key from-end start end count key)
1884   #!+sb-doc
1885   "Return a sequence of the same kind as SEQUENCE with the same elements
1886    except that all elements satisfying the TEST are replaced with NEW. 
1887    SEQUENCE may be destructively modified. See manual for details."
1888   (declare (fixnum start))
1889   (let ((end (or end length)))
1890     (declare (fixnum end))
1891     (if (listp sequence)
1892         (if from-end
1893             (let ((length (length sequence)))
1894               (nreverse (nlist-substitute-if*
1895                          new test (nreverse (the list sequence))
1896                          (- length end) (- length start) count key)))
1897             (nlist-substitute-if* new test sequence
1898                                   start end count key))
1899         (if from-end
1900             (nvector-substitute-if* new test sequence -1
1901                                     (1- end) (1- start) count key)
1902             (nvector-substitute-if* new test sequence 1
1903                                     start end count key)))))
1904
1905 (defun nlist-substitute-if* (new test sequence start end count key)
1906   (declare (fixnum end))
1907   (do ((list (nthcdr start sequence) (cdr list))
1908        (index start (1+ index)))
1909       ((or (= index end) (null list) (= count 0)) sequence)
1910     (when (funcall test (apply-key key (car list)))
1911       (rplaca list new)
1912       (setq count (1- count)))))
1913
1914 (defun nvector-substitute-if* (new test sequence incrementer
1915                                start end count key)
1916   (do ((index start (+ index incrementer)))
1917       ((or (= index end) (= count 0)) sequence)
1918     (when (funcall test (apply-key key (aref sequence index)))
1919       (setf (aref sequence index) new)
1920       (setq count (1- count)))))
1921
1922 (define-sequence-traverser nsubstitute-if-not
1923     (new test sequence &key from-end start end count key)
1924   #!+sb-doc
1925   "Return a sequence of the same kind as SEQUENCE with the same elements
1926    except that all elements not satisfying the TEST are replaced with NEW.
1927    SEQUENCE may be destructively modified. See manual for details."
1928   (declare (fixnum start))
1929   (let ((end (or end length)))
1930     (declare (fixnum end))
1931     (if (listp sequence)
1932         (if from-end
1933             (let ((length (length sequence)))
1934               (nreverse (nlist-substitute-if-not*
1935                          new test (nreverse (the list sequence))
1936                          (- length end) (- length start) count key)))
1937             (nlist-substitute-if-not* new test sequence
1938                                       start end count key))
1939         (if from-end
1940             (nvector-substitute-if-not* new test sequence -1
1941                                         (1- end) (1- start) count key)
1942             (nvector-substitute-if-not* new test sequence 1
1943                                         start end count key)))))
1944
1945 (defun nlist-substitute-if-not* (new test sequence start end count key)
1946   (declare (fixnum end))
1947   (do ((list (nthcdr start sequence) (cdr list))
1948        (index start (1+ index)))
1949       ((or (= index end) (null list) (= count 0)) sequence)
1950     (when (not (funcall test (apply-key key (car list))))
1951       (rplaca list new)
1952       (decf count))))
1953
1954 (defun nvector-substitute-if-not* (new test sequence incrementer
1955                                    start end count key)
1956   (do ((index start (+ index incrementer)))
1957       ((or (= index end) (= count 0)) sequence)
1958     (when (not (funcall test (apply-key key (aref sequence index))))
1959       (setf (aref sequence index) new)
1960       (decf count))))
1961 \f
1962 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
1963
1964 (defun effective-find-position-test (test test-not)
1965   (effective-find-position-test test test-not))
1966 (defun effective-find-position-key (key)
1967   (effective-find-position-key key))
1968
1969 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
1970 (macrolet (;; shared logic for defining %FIND-POSITION and
1971            ;; %FIND-POSITION-IF in terms of various inlineable cases
1972            ;; of the expression defined in FROB and VECTOR*-FROB
1973            (frobs ()
1974              `(etypecase sequence-arg
1975                 (list (frob sequence-arg from-end))
1976                 (vector
1977                  (with-array-data ((sequence sequence-arg :offset-var offset)
1978                                    (start start)
1979                                    (end (%check-vector-sequence-bounds
1980                                          sequence-arg start end)))
1981                    (multiple-value-bind (f p)
1982                        (macrolet ((frob2 () '(if from-end
1983                                                  (frob sequence t)
1984                                                  (frob sequence nil))))
1985                          (typecase sequence
1986                            (simple-vector (frob2))
1987                            (simple-base-string (frob2))
1988                            (t (vector*-frob sequence))))
1989                      (declare (type (or index null) p))
1990                      (values f (and p (the index (+ p offset))))))))))
1991   (defun %find-position (item sequence-arg from-end start end key test)
1992     (macrolet ((frob (sequence from-end)
1993                  `(%find-position item ,sequence
1994                                   ,from-end start end key test))
1995                (vector*-frob (sequence)
1996                  `(%find-position-vector-macro item ,sequence
1997                                                from-end start end key test)))
1998       (frobs)))
1999   (defun %find-position-if (predicate sequence-arg from-end start end key)
2000     (macrolet ((frob (sequence from-end)
2001                  `(%find-position-if predicate ,sequence
2002                                      ,from-end start end key))
2003                (vector*-frob (sequence)
2004                  `(%find-position-if-vector-macro predicate ,sequence
2005                                                   from-end start end key)))
2006       (frobs)))
2007   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
2008     (macrolet ((frob (sequence from-end)
2009                  `(%find-position-if-not predicate ,sequence
2010                                          ,from-end start end key))
2011                (vector*-frob (sequence)
2012                  `(%find-position-if-not-vector-macro predicate ,sequence
2013                                                   from-end start end key)))
2014       (frobs))))
2015
2016 ;;; the user interface to FIND and POSITION: just interpreter stubs,
2017 ;;; nowadays.
2018 (defun find (item sequence &key from-end (start 0) end key test test-not)
2019   ;; FIXME: this can't be the way to go, surely?
2020   (find item sequence :from-end from-end :start start :end end :key key
2021         :test test :test-not test-not))
2022 (defun position (item sequence &key from-end (start 0) end key test test-not)
2023   (position item sequence :from-end from-end :start start :end end :key key
2024             :test test :test-not test-not))
2025
2026 ;;; the user interface to FIND-IF and POSITION-IF, entirely analogous
2027 ;;; to the interface to FIND and POSITION
2028 (defun find-if (predicate sequence &key from-end (start 0) end key)
2029   (find-if predicate sequence :from-end from-end :start start
2030            :end end :key key))
2031 (defun position-if (predicate sequence &key from-end (start 0) end key)
2032   (position-if predicate sequence :from-end from-end :start start
2033                :end end :key key))
2034
2035 (defun find-if-not (predicate sequence &key from-end (start 0) end key)
2036   (find-if-not predicate sequence :from-end from-end :start start
2037            :end end :key key))
2038 (defun position-if-not (predicate sequence &key from-end (start 0) end key)
2039   (position-if-not predicate sequence :from-end from-end :start start
2040                :end end :key key))
2041 \f
2042 ;;;; COUNT-IF, COUNT-IF-NOT, and COUNT
2043
2044 (eval-when (:compile-toplevel :execute)
2045
2046 (sb!xc:defmacro vector-count-if (notp from-end-p predicate sequence)
2047   (let ((next-index (if from-end-p '(1- index) '(1+ index)))
2048         (pred `(funcall ,predicate (apply-key key (aref ,sequence index)))))
2049     `(let ((%start ,(if from-end-p '(1- end) 'start))
2050            (%end ,(if from-end-p '(1- start) 'end)))
2051       (do ((index %start ,next-index)
2052            (count 0))
2053           ((= index (the fixnum %end)) count)
2054         (declare (fixnum index count))
2055         (,(if notp 'unless 'when) ,pred
2056           (setq count (1+ count)))))))
2057
2058 (sb!xc:defmacro list-count-if (notp from-end-p predicate sequence)
2059   (let ((pred `(funcall ,predicate (apply-key key (pop sequence)))))
2060     `(let ((%start ,(if from-end-p '(- length end) 'start))
2061            (%end ,(if from-end-p '(- length start) 'end))
2062            (sequence ,(if from-end-p '(reverse sequence) 'sequence)))
2063       (do ((sequence (nthcdr %start ,sequence))
2064            (index %start (1+ index))
2065            (count 0))
2066           ((or (= index (the fixnum %end)) (null sequence)) count)
2067         (declare (fixnum index count))
2068         (,(if notp 'unless 'when) ,pred
2069           (setq count (1+ count)))))))
2070
2071
2072 ) ; EVAL-WHEN
2073
2074 (define-sequence-traverser count-if (test sequence &key from-end start end key)
2075   #!+sb-doc
2076   "Return the number of elements in SEQUENCE satisfying TEST(el)."
2077   (declare (fixnum start))
2078   (let ((end (or end length)))
2079     (declare (type index end))
2080     (seq-dispatch sequence
2081                   (if from-end
2082                       (list-count-if nil t test sequence)
2083                       (list-count-if nil nil test sequence))
2084                   (if from-end
2085                       (vector-count-if nil t test sequence)
2086                       (vector-count-if nil nil test sequence)))))
2087
2088 (define-sequence-traverser count-if-not
2089     (test sequence &key from-end start end key)
2090   #!+sb-doc
2091   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2092   (declare (fixnum start))
2093   (let ((end (or end length)))
2094     (declare (type index end))
2095     (seq-dispatch sequence
2096                   (if from-end
2097                       (list-count-if t t test sequence)
2098                       (list-count-if t nil test sequence))
2099                   (if from-end
2100                       (vector-count-if t t test sequence)
2101                       (vector-count-if t nil test sequence)))))
2102
2103 (define-sequence-traverser count
2104     (item sequence &key from-end start end
2105           key (test #'eql test-p) (test-not nil test-not-p))
2106   #!+sb-doc
2107   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2108    which defaults to EQL."
2109   (declare (fixnum start))
2110   (when (and test-p test-not-p)
2111     ;; ANSI Common Lisp has left the behavior in this situation unspecified.
2112     ;; (CLHS 17.2.1)
2113     (error ":TEST and :TEST-NOT are both present."))
2114   (let ((end (or end length)))
2115     (declare (type index end))
2116     (let ((%test (if test-not-p
2117                      (lambda (x)
2118                        (not (funcall test-not item x)))
2119                      (lambda (x)
2120                        (funcall test item x)))))
2121       (seq-dispatch sequence
2122                     (if from-end
2123                         (list-count-if nil t %test sequence)
2124                         (list-count-if nil nil %test sequence))
2125                     (if from-end
2126                         (vector-count-if nil t %test sequence)
2127                         (vector-count-if nil nil %test sequence))))))
2128
2129
2130 \f
2131 ;;;; MISMATCH
2132
2133 (eval-when (:compile-toplevel :execute)
2134
2135 (sb!xc:defmacro match-vars (&rest body)
2136   `(let ((inc (if from-end -1 1))
2137          (start1 (if from-end (1- (the fixnum end1)) start1))
2138          (start2 (if from-end (1- (the fixnum end2)) start2))
2139          (end1 (if from-end (1- (the fixnum start1)) end1))
2140          (end2 (if from-end (1- (the fixnum start2)) end2)))
2141      (declare (fixnum inc start1 start2 end1 end2))
2142      ,@body))
2143
2144 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2145   (declare (ignore end)) ;; ### Should END be used below?
2146   `(let ((,sequence (if from-end
2147                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2148                                 (reverse (the list ,sequence)))
2149                         (nthcdr ,start ,sequence))))
2150      (declare (type list ,sequence))
2151      ,@body))
2152
2153 ) ; EVAL-WHEN
2154
2155 (eval-when (:compile-toplevel :execute)
2156
2157 (sb!xc:defmacro if-mismatch (elt1 elt2)
2158   `(cond ((= (the fixnum index1) (the fixnum end1))
2159           (return (if (= (the fixnum index2) (the fixnum end2))
2160                       nil
2161                       (if from-end
2162                           (1+ (the fixnum index1))
2163                           (the fixnum index1)))))
2164          ((= (the fixnum index2) (the fixnum end2))
2165           (return (if from-end (1+ (the fixnum index1)) index1)))
2166          (test-not
2167           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2168               (return (if from-end (1+ (the fixnum index1)) index1))))
2169          (t (if (not (funcall test (apply-key key ,elt1)
2170                               (apply-key key ,elt2)))
2171                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2172
2173 (sb!xc:defmacro mumble-mumble-mismatch ()
2174   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2175         (index2 start2 (+ index2 (the fixnum inc))))
2176        (())
2177      (declare (fixnum index1 index2))
2178      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2179
2180 (sb!xc:defmacro mumble-list-mismatch ()
2181   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2182         (index2 start2 (+ index2 (the fixnum inc))))
2183        (())
2184      (declare (fixnum index1 index2))
2185      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2186 \f
2187 (sb!xc:defmacro list-mumble-mismatch ()
2188   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2189         (index2 start2 (+ index2 (the fixnum inc))))
2190        (())
2191      (declare (fixnum index1 index2))
2192      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2193
2194 (sb!xc:defmacro list-list-mismatch ()
2195   `(do ((sequence1 sequence1)
2196         (sequence2 sequence2)
2197         (index1 start1 (+ index1 (the fixnum inc)))
2198         (index2 start2 (+ index2 (the fixnum inc))))
2199        (())
2200      (declare (fixnum index1 index2))
2201      (if-mismatch (pop sequence1) (pop sequence2))))
2202
2203 ) ; EVAL-WHEN
2204
2205 (define-sequence-traverser mismatch
2206     (sequence1 sequence2
2207                &key from-end (test #'eql) test-not
2208                start1 end1 start2 end2 key)
2209   #!+sb-doc
2210   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2211    element-wise. If they are of equal length and match in every element, the
2212    result is NIL. Otherwise, the result is a non-negative integer, the index
2213    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2214    if one is shorter than and a matching prefix of the other, the index within
2215    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2216    :FROM-END argument is given, then one plus the index of the rightmost
2217    position in which the sequences differ is returned."
2218   (declare (fixnum start1 start2))
2219   (let* ((end1 (or end1 length1))
2220          (end2 (or end2 length2)))
2221     (declare (type index end1 end2))
2222     (match-vars
2223      (seq-dispatch sequence1
2224        (matchify-list (sequence1 start1 length1 end1)
2225          (seq-dispatch sequence2
2226            (matchify-list (sequence2 start2 length2 end2)
2227              (list-list-mismatch))
2228            (list-mumble-mismatch)))
2229        (seq-dispatch sequence2
2230          (matchify-list (sequence2 start2 length2 end2)
2231            (mumble-list-mismatch))
2232          (mumble-mumble-mismatch))))))
2233 \f
2234 ;;; search comparison functions
2235
2236 (eval-when (:compile-toplevel :execute)
2237
2238 ;;; Compare two elements and return if they don't match.
2239 (sb!xc:defmacro compare-elements (elt1 elt2)
2240   `(if test-not
2241        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2242            (return nil)
2243            t)
2244        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2245            (return nil)
2246            t)))
2247
2248 (sb!xc:defmacro search-compare-list-list (main sub)
2249   `(do ((main ,main (cdr main))
2250         (jndex start1 (1+ jndex))
2251         (sub (nthcdr start1 ,sub) (cdr sub)))
2252        ((or (null main) (null sub) (= (the fixnum end1) jndex))
2253         t)
2254      (declare (fixnum jndex))
2255      (compare-elements (car sub) (car main))))
2256
2257 (sb!xc:defmacro search-compare-list-vector (main sub)
2258   `(do ((main ,main (cdr main))
2259         (index start1 (1+ index)))
2260        ((or (null main) (= index (the fixnum end1))) t)
2261      (declare (fixnum index))
2262      (compare-elements (aref ,sub index) (car main))))
2263
2264 (sb!xc:defmacro search-compare-vector-list (main sub index)
2265   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2266         (jndex start1 (1+ jndex))
2267         (index ,index (1+ index)))
2268        ((or (= (the fixnum end1) jndex) (null sub)) t)
2269      (declare (fixnum jndex index))
2270      (compare-elements (car sub) (aref ,main index))))
2271
2272 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2273   `(do ((index ,index (1+ index))
2274         (sub-index start1 (1+ sub-index)))
2275        ((= sub-index (the fixnum end1)) t)
2276      (declare (fixnum sub-index index))
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 (- (the fixnum end2)
2298                      (the fixnum (- (the fixnum end1)
2299                                     (the fixnum start1)))))
2300         (last-match ()))
2301        ((> index2 terminus) last-match)
2302      (declare (fixnum index2 terminus))
2303      (if (search-compare list main ,sub index2)
2304          (if from-end
2305              (setq last-match index2)
2306              (return index2)))))
2307
2308 (sb!xc:defmacro vector-search (main sub)
2309   `(do ((index2 start2 (1+ index2))
2310         (terminus (- (the fixnum end2)
2311                      (the fixnum (- (the fixnum end1)
2312                                     (the fixnum start1)))))
2313         (last-match ()))
2314        ((> index2 terminus) last-match)
2315      (declare (fixnum index2 terminus))
2316      (if (search-compare vector ,main ,sub index2)
2317          (if from-end
2318              (setq last-match index2)
2319              (return index2)))))
2320
2321 ) ; EVAL-WHEN
2322
2323 (define-sequence-traverser search
2324     (sequence1 sequence2
2325                &key from-end (test #'eql) test-not
2326                start1 end1 start2 end2 key)
2327   (declare (fixnum start1 start2))
2328   (let ((end1 (or end1 length1))
2329         (end2 (or end2 length2)))
2330     (seq-dispatch sequence2
2331                   (list-search sequence2 sequence1)
2332                   (vector-search sequence2 sequence1))))