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