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