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