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