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