0.7.8.43:
[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           (%start ,(if reverse? '(- length end) 'start))
1273           (%end ,(if reverse? '(- length start) 'end))
1274           (splice (list nil))
1275           (results (do ((index 0 (1+ index))
1276                         (before-start splice))
1277                        ((= index (the fixnum %start)) before-start)
1278                      (declare (fixnum index))
1279                      (setq splice
1280                            (cdr (rplacd splice (list (pop sequence))))))))
1281      (do ((index %start (1+ index))
1282           (this-element)
1283           (number-zapped 0))
1284          ((or (= index (the fixnum %end)) (= number-zapped (the fixnum count)))
1285           (do ((index index (1+ index)))
1286               ((null sequence)
1287                ,(if reverse?
1288                     '(nreverse (the list (cdr results)))
1289                     '(cdr results)))
1290             (declare (fixnum index))
1291             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1292        (declare (fixnum index number-zapped))
1293        (setq this-element (pop sequence))
1294        (if ,pred
1295            (setq number-zapped (1+ number-zapped))
1296            (setq splice (cdr (rplacd splice (list this-element))))))))
1297
1298 (sb!xc:defmacro list-remove (pred)
1299   `(list-remove-macro ,pred nil))
1300
1301 (sb!xc:defmacro list-remove-from-end (pred)
1302   `(list-remove-macro ,pred t))
1303
1304 (sb!xc:defmacro normal-list-remove ()
1305   `(list-remove
1306     (if test-not
1307         (not (funcall test-not item (apply-key key this-element)))
1308         (funcall test item (apply-key key this-element)))))
1309
1310 (sb!xc:defmacro normal-list-remove-from-end ()
1311   `(list-remove-from-end
1312     (if test-not
1313         (not (funcall test-not item (apply-key key this-element)))
1314         (funcall test item (apply-key key this-element)))))
1315
1316 (sb!xc:defmacro if-list-remove ()
1317   `(list-remove
1318     (funcall predicate (apply-key key this-element))))
1319
1320 (sb!xc:defmacro if-list-remove-from-end ()
1321   `(list-remove-from-end
1322     (funcall predicate (apply-key key this-element))))
1323
1324 (sb!xc:defmacro if-not-list-remove ()
1325   `(list-remove
1326     (not (funcall predicate (apply-key key this-element)))))
1327
1328 (sb!xc:defmacro if-not-list-remove-from-end ()
1329   `(list-remove-from-end
1330     (not (funcall predicate (apply-key key this-element)))))
1331
1332 ) ; EVAL-WHEN
1333
1334 (defun remove (item sequence &key from-end (test #'eql) test-not (start 0)
1335                 end count key)
1336   #!+sb-doc
1337   "Return a copy of SEQUENCE with elements satisfying the test (default is
1338    EQL) with ITEM removed."
1339   (declare (fixnum start))
1340   (let* ((length (length sequence))
1341          (end (or end length))
1342          (count (adjust-count count)))
1343     (declare (type index length end)
1344              (fixnum count))
1345     (seq-dispatch sequence
1346                   (if from-end
1347                       (normal-list-remove-from-end)
1348                       (normal-list-remove))
1349                   (if from-end
1350                       (normal-mumble-remove-from-end)
1351                       (normal-mumble-remove)))))
1352
1353 (defun remove-if (predicate sequence &key from-end (start 0) end count key)
1354   #!+sb-doc
1355   "Return a copy of sequence with elements such that predicate(element)
1356    is non-null removed"
1357   (declare (fixnum start))
1358   (let* ((length (length sequence))
1359          (end (or end length))
1360          (count (adjust-count count)))
1361     (declare (type index length end)
1362              (fixnum count))
1363     (seq-dispatch sequence
1364                   (if from-end
1365                       (if-list-remove-from-end)
1366                       (if-list-remove))
1367                   (if from-end
1368                       (if-mumble-remove-from-end)
1369                       (if-mumble-remove)))))
1370
1371 (defun remove-if-not (predicate sequence &key from-end (start 0) end count key)
1372   #!+sb-doc
1373   "Return a copy of sequence with elements such that predicate(element)
1374    is null removed"
1375   (declare (fixnum start))
1376   (let* ((length (length sequence))
1377          (end (or end length))
1378          (count (adjust-count count)))
1379     (declare (type index length end)
1380              (fixnum count))
1381     (seq-dispatch sequence
1382                   (if from-end
1383                       (if-not-list-remove-from-end)
1384                       (if-not-list-remove))
1385                   (if from-end
1386                       (if-not-mumble-remove-from-end)
1387                       (if-not-mumble-remove)))))
1388 \f
1389 ;;;; REMOVE-DUPLICATES
1390
1391 ;;; Remove duplicates from a list. If from-end, remove the later duplicates,
1392 ;;; not the earlier ones. Thus if we check from-end we don't copy an item
1393 ;;; if we look into the already copied structure (from after :start) and see
1394 ;;; the item. If we check from beginning we check into the rest of the
1395 ;;; original list up to the :end marker (this we have to do by running a
1396 ;;; do loop down the list that far and using our test.
1397 (defun list-remove-duplicates* (list test test-not start end key from-end)
1398   (declare (fixnum start))
1399   (let* ((result (list ())) ; Put a marker on the beginning to splice with.
1400          (splice result)
1401          (current list))
1402     (do ((index 0 (1+ index)))
1403         ((= index start))
1404       (declare (fixnum index))
1405       (setq splice (cdr (rplacd splice (list (car current)))))
1406       (setq current (cdr current)))
1407     (do ((index 0 (1+ index)))
1408         ((or (and end (= index (the fixnum end)))
1409              (atom current)))
1410       (declare (fixnum index))
1411       (if (or (and from-end
1412                    (not (member (apply-key key (car current))
1413                                 (nthcdr (1+ start) result)
1414                                 :test test
1415                                 :test-not test-not
1416                                 :key key)))
1417               (and (not from-end)
1418                    (not (do ((it (apply-key key (car current)))
1419                              (l (cdr current) (cdr l))
1420                              (i (1+ index) (1+ i)))
1421                             ((or (atom l) (and end (= i (the fixnum end))))
1422                              ())
1423                           (declare (fixnum i))
1424                           (if (if test-not
1425                                   (not (funcall test-not it (apply-key key (car l))))
1426                                   (funcall test it (apply-key key (car l))))
1427                               (return t))))))
1428           (setq splice (cdr (rplacd splice (list (car current))))))
1429       (setq current (cdr current)))
1430     (do ()
1431         ((atom current))
1432       (setq splice (cdr (rplacd splice (list (car current)))))
1433       (setq current (cdr current)))
1434     (cdr result)))
1435
1436 (defun vector-remove-duplicates* (vector test test-not start end key from-end
1437                                          &optional (length (length vector)))
1438   (declare (vector vector) (fixnum start length))
1439   (when (null end) (setf end (length vector)))
1440   (let ((result (make-sequence-like vector length))
1441         (index 0)
1442         (jndex start))
1443     (declare (fixnum index jndex))
1444     (do ()
1445         ((= index start))
1446       (setf (aref result index) (aref vector index))
1447       (setq index (1+ index)))
1448     (do ((elt))
1449         ((= index end))
1450       (setq elt (aref vector index))
1451       (unless (or (and from-end
1452                         (position (apply-key key elt) result :start start
1453                            :end jndex :test test :test-not test-not :key key))
1454                   (and (not from-end)
1455                         (position (apply-key key elt) vector :start (1+ index)
1456                            :end end :test test :test-not test-not :key key)))
1457         (setf (aref result jndex) elt)
1458         (setq jndex (1+ jndex)))
1459       (setq index (1+ index)))
1460     (do ()
1461         ((= index length))
1462       (setf (aref result jndex) (aref vector index))
1463       (setq index (1+ index))
1464       (setq jndex (1+ jndex)))
1465     (shrink-vector result jndex)))
1466
1467 (defun remove-duplicates (sequence &key
1468                                    (test #'eql)
1469                                    test-not
1470                                    (start 0)
1471                                    from-end
1472                                    end
1473                                    key)
1474   #!+sb-doc
1475   "The elements of Sequence are compared pairwise, and if any two match,
1476    the one occurring earlier is discarded, unless FROM-END is true, in
1477    which case the one later in the sequence is discarded. The resulting
1478    sequence is returned.
1479
1480    The :TEST-NOT argument is depreciated."
1481   (declare (fixnum start))
1482   (seq-dispatch sequence
1483                 (if sequence
1484                     (list-remove-duplicates* sequence test test-not
1485                                               start end key from-end))
1486                 (vector-remove-duplicates* sequence test test-not
1487                                             start end key from-end)))
1488 \f
1489 ;;;; DELETE-DUPLICATES
1490
1491 (defun list-delete-duplicates* (list test test-not key from-end start end)
1492   (declare (fixnum start))
1493   (let ((handle (cons nil list)))
1494     (do ((current (nthcdr start list) (cdr current))
1495          (previous (nthcdr start handle))
1496          (index start (1+ index)))
1497         ((or (and end (= index (the fixnum end))) (null current))
1498          (cdr handle))
1499       (declare (fixnum index))
1500       (if (do ((x (if from-end
1501                       (nthcdr (1+ start) handle)
1502                       (cdr current))
1503                   (cdr x))
1504                (i (1+ index) (1+ i)))
1505               ((or (null x)
1506                    (and (not from-end) end (= i (the fixnum end)))
1507                    (eq x current))
1508                nil)
1509             (declare (fixnum i))
1510             (if (if test-not
1511                     (not (funcall test-not
1512                                   (apply-key key (car current))
1513                                   (apply-key key (car x))))
1514                     (funcall test
1515                              (apply-key key (car current))
1516                              (apply-key key (car x))))
1517                 (return t)))
1518           (rplacd previous (cdr current))
1519           (setq previous (cdr previous))))))
1520
1521 (defun vector-delete-duplicates* (vector test test-not key from-end start end
1522                                          &optional (length (length vector)))
1523   (declare (vector vector) (fixnum start length))
1524   (when (null end) (setf end (length vector)))
1525   (do ((index start (1+ index))
1526        (jndex start))
1527       ((= index end)
1528        (do ((index index (1+ index))            ; copy the rest of the vector
1529             (jndex jndex (1+ jndex)))
1530            ((= index length)
1531             (shrink-vector vector jndex)
1532             vector)
1533          (setf (aref vector jndex) (aref vector index))))
1534     (declare (fixnum index jndex))
1535     (setf (aref vector jndex) (aref vector index))
1536     (unless (position (apply-key key (aref vector index)) vector :key key
1537                       :start (if from-end start (1+ index)) :test test
1538                       :end (if from-end jndex end) :test-not test-not)
1539       (setq jndex (1+ jndex)))))
1540
1541 (defun delete-duplicates (sequence &key
1542                                    (test #'eql)
1543                                    test-not
1544                                    (start 0)
1545                                    from-end
1546                                    end
1547                                    key)
1548   #!+sb-doc
1549   "The elements of Sequence are examined, and if any two match, one is
1550    discarded. The resulting sequence, which may be formed by destroying the
1551    given sequence, is returned.
1552
1553    The :TEST-NOT argument is depreciated."
1554   (seq-dispatch sequence
1555     (if sequence
1556         (list-delete-duplicates* sequence test test-not key from-end start end))
1557   (vector-delete-duplicates* sequence test test-not key from-end start end)))
1558 \f
1559 ;;;; SUBSTITUTE
1560
1561 (defun list-substitute* (pred new list start end count key test test-not old)
1562   (declare (fixnum start end count))
1563   (let* ((result (list nil))
1564          elt
1565          (splice result)
1566          (list list))      ; Get a local list for a stepper.
1567     (do ((index 0 (1+ index)))
1568         ((= index start))
1569       (declare (fixnum index))
1570       (setq splice (cdr (rplacd splice (list (car list)))))
1571       (setq list (cdr list)))
1572     (do ((index start (1+ index)))
1573         ((or (= index end) (null list) (= count 0)))
1574       (declare (fixnum index))
1575       (setq elt (car list))
1576       (setq splice
1577             (cdr (rplacd splice
1578                          (list
1579                           (cond
1580                            ((case pred
1581                                    (normal
1582                                     (if test-not
1583                                         (not
1584                                          (funcall test-not old (apply-key key elt)))
1585                                         (funcall test old (apply-key key elt))))
1586                                    (if (funcall test (apply-key key elt)))
1587                                    (if-not (not (funcall test (apply-key key elt)))))
1588                             (setq count (1- count))
1589                             new)
1590                                 (t elt))))))
1591       (setq list (cdr list)))
1592     (do ()
1593         ((null list))
1594       (setq splice (cdr (rplacd splice (list (car list)))))
1595       (setq list (cdr list)))
1596     (cdr result)))
1597
1598 ;;; Replace old with new in sequence moving from left to right by incrementer
1599 ;;; on each pass through the loop. Called by all three substitute functions.
1600 (defun vector-substitute* (pred new sequence incrementer left right length
1601                            start end count key test test-not old)
1602   (declare (fixnum start count end incrementer right))
1603   (let ((result (make-sequence-like sequence length))
1604         (index left))
1605     (declare (fixnum index))
1606     (do ()
1607         ((= index start))
1608       (setf (aref result index) (aref sequence index))
1609       (setq index (+ index incrementer)))
1610     (do ((elt))
1611         ((or (= index end) (= count 0)))
1612       (setq elt (aref sequence index))
1613       (setf (aref result index)
1614             (cond ((case pred
1615                           (normal
1616                             (if test-not
1617                                 (not (funcall test-not old (apply-key key elt)))
1618                                 (funcall test old (apply-key key elt))))
1619                           (if (funcall test (apply-key key elt)))
1620                           (if-not (not (funcall test (apply-key key elt)))))
1621                    (setq count (1- count))
1622                    new)
1623                   (t elt)))
1624       (setq index (+ index incrementer)))
1625     (do ()
1626         ((= index right))
1627       (setf (aref result index) (aref sequence index))
1628       (setq index (+ index incrementer)))
1629     result))
1630
1631 (eval-when (:compile-toplevel :execute)
1632
1633 (sb!xc:defmacro subst-dispatch (pred)
1634   `(if (listp sequence)
1635        (if from-end
1636            (nreverse (list-substitute* ,pred
1637                                        new
1638                                        (reverse sequence)
1639                                        (- (the fixnum length)
1640                                           (the fixnum end))
1641                                        (- (the fixnum length)
1642                                           (the fixnum start))
1643                                        count key test test-not old))
1644            (list-substitute* ,pred
1645                              new sequence start end count key test test-not
1646                              old))
1647       (if from-end
1648           (vector-substitute* ,pred new sequence -1 (1- (the fixnum length))
1649                               -1 length (1- (the fixnum end))
1650                               (1- (the fixnum start))
1651                               count key test test-not old)
1652           (vector-substitute* ,pred new sequence 1 0 length length
1653            start end count key test test-not old))))
1654
1655 ) ; EVAL-WHEN
1656
1657 (defun substitute (new old sequence &key from-end (test #'eql) test-not
1658                    (start 0) count end key)
1659   #!+sb-doc
1660   "Return a sequence of the same kind as SEQUENCE with the same elements,
1661   except that all elements equal to OLD are replaced with NEW. See manual
1662   for details."
1663   (declare (fixnum start))
1664   (let* ((length (length sequence))
1665          (end (or end length))
1666          (count (adjust-count count)))
1667     (declare (type index length end)
1668              (fixnum count))
1669     (subst-dispatch 'normal)))
1670 \f
1671 ;;;; SUBSTITUTE-IF, SUBSTITUTE-IF-NOT
1672
1673 (defun substitute-if (new test sequence &key from-end (start 0) end count key)
1674   #!+sb-doc
1675   "Return a sequence of the same kind as SEQUENCE with the same elements
1676   except that all elements satisfying the TEST are replaced with NEW. See
1677   manual for details."
1678   (declare (fixnum start))
1679   (let* ((length (length sequence))
1680          (end (or end length))
1681          (count (adjust-count count))
1682          test-not
1683          old)
1684     (declare (type index length end)
1685              (fixnum count))
1686     (subst-dispatch 'if)))
1687
1688 (defun substitute-if-not (new test sequence &key from-end (start 0)
1689                            end count key)
1690   #!+sb-doc
1691   "Return a sequence of the same kind as SEQUENCE with the same elements
1692   except that all elements not satisfying the TEST are replaced with NEW.
1693   See manual for details."
1694   (declare (fixnum start))
1695   (let* ((length (length sequence))
1696          (end (or end length))
1697          (count (adjust-count count))
1698          test-not
1699          old)
1700     (declare (type index length end)
1701              (fixnum count))
1702     (subst-dispatch 'if-not)))
1703 \f
1704 ;;;; NSUBSTITUTE
1705
1706 (defun nsubstitute (new old sequence &key from-end (test #'eql) test-not
1707                      end count key (start 0))
1708   #!+sb-doc
1709   "Return a sequence of the same kind as SEQUENCE with the same elements
1710   except that all elements equal to OLD are replaced with NEW. The SEQUENCE
1711   may be destructively modified. See manual for details."
1712   (declare (fixnum start))
1713   (let ((end (or end (length sequence)))
1714         (count (adjust-count count)))
1715     (declare (fixnum count))
1716     (if (listp sequence)
1717         (if from-end
1718             (nreverse (nlist-substitute*
1719                        new old (nreverse (the list sequence))
1720                        test test-not start end count key))
1721             (nlist-substitute* new old sequence
1722                                test test-not start end count key))
1723         (if from-end
1724             (nvector-substitute* new old sequence -1
1725                                  test test-not (1- end) (1- start) count key)
1726             (nvector-substitute* new old sequence 1
1727                                  test test-not start end count key)))))
1728
1729 (defun nlist-substitute* (new old sequence test test-not start end count key)
1730   (declare (fixnum start count end))
1731   (do ((list (nthcdr start sequence) (cdr list))
1732        (index start (1+ index)))
1733       ((or (= index end) (null list) (= count 0)) sequence)
1734     (declare (fixnum index))
1735     (when (if test-not
1736               (not (funcall test-not old (apply-key key (car list))))
1737               (funcall test old (apply-key key (car list))))
1738       (rplaca list new)
1739       (setq count (1- count)))))
1740
1741 (defun nvector-substitute* (new old sequence incrementer
1742                             test test-not start end count key)
1743   (declare (fixnum start incrementer count end))
1744   (do ((index start (+ index incrementer)))
1745       ((or (= index end) (= count 0)) sequence)
1746     (declare (fixnum index))
1747     (when (if test-not
1748               (not (funcall test-not
1749                             old
1750                             (apply-key key (aref sequence index))))
1751               (funcall test old (apply-key key (aref sequence index))))
1752       (setf (aref sequence index) new)
1753       (setq count (1- count)))))
1754 \f
1755 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
1756
1757 (defun nsubstitute-if (new test sequence &key from-end (start 0) end count key)
1758   #!+sb-doc
1759   "Return a sequence of the same kind as SEQUENCE with the same elements
1760    except that all elements satisfying the TEST are replaced with NEW. 
1761    SEQUENCE may be destructively modified. See manual for details."
1762   (declare (fixnum start))
1763   (let ((end (or end (length sequence)))
1764         (count (adjust-count count)))
1765     (declare (fixnum end count))
1766     (if (listp sequence)
1767         (if from-end
1768             (nreverse (nlist-substitute-if*
1769                        new test (nreverse (the list sequence))
1770                        start end count key))
1771             (nlist-substitute-if* new test sequence
1772                                   start end count key))
1773         (if from-end
1774             (nvector-substitute-if* new test sequence -1
1775                                     (1- end) (1- start) count key)
1776             (nvector-substitute-if* new test sequence 1
1777                                     start end count key)))))
1778
1779 (defun nlist-substitute-if* (new test sequence start end count key)
1780   (declare (fixnum end))
1781   (do ((list (nthcdr start sequence) (cdr list))
1782        (index start (1+ index)))
1783       ((or (= index end) (null list) (= count 0)) sequence)
1784     (when (funcall test (apply-key key (car list)))
1785       (rplaca list new)
1786       (setq count (1- count)))))
1787
1788 (defun nvector-substitute-if* (new test sequence incrementer
1789                                start end count key)
1790   (do ((index start (+ index incrementer)))
1791       ((or (= index end) (= count 0)) sequence)
1792     (when (funcall test (apply-key key (aref sequence index)))
1793       (setf (aref sequence index) new)
1794       (setq count (1- count)))))
1795
1796 (defun nsubstitute-if-not (new test sequence &key from-end (start 0)
1797                                end count key)
1798   #!+sb-doc
1799   "Return a sequence of the same kind as SEQUENCE with the same elements
1800    except that all elements not satisfying the TEST are replaced with NEW.
1801    SEQUENCE may be destructively modified. See manual for details."
1802   (declare (fixnum start))
1803   (let ((end (or end (length sequence)))
1804         (count (adjust-count count)))
1805     (declare (fixnum end count))
1806     (if (listp sequence)
1807         (if from-end
1808             (nreverse (nlist-substitute-if-not*
1809                        new test (nreverse (the list sequence))
1810                        start end count key))
1811             (nlist-substitute-if-not* new test sequence
1812                                       start end count key))
1813         (if from-end
1814             (nvector-substitute-if-not* new test sequence -1
1815                                         (1- end) (1- start) count key)
1816             (nvector-substitute-if-not* new test sequence 1
1817                                         start end count key)))))
1818
1819 (defun nlist-substitute-if-not* (new test sequence start end count key)
1820   (declare (fixnum end))
1821   (do ((list (nthcdr start sequence) (cdr list))
1822        (index start (1+ index)))
1823       ((or (= index end) (null list) (= count 0)) sequence)
1824     (when (not (funcall test (apply-key key (car list))))
1825       (rplaca list new)
1826       (setq count (1- count)))))
1827
1828 (defun nvector-substitute-if-not* (new test sequence incrementer
1829                                    start end count key)
1830   (do ((index start (+ index incrementer)))
1831       ((or (= index end) (= count 0)) sequence)
1832     (when (not (funcall test (apply-key key (aref sequence index))))
1833       (setf (aref sequence index) new)
1834       (setq count (1- count)))))
1835 \f
1836 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
1837
1838 ;;; logic to unravel :TEST, :TEST-NOT, and :KEY options in FIND,
1839 ;;; POSITION-IF, etc.
1840 (declaim (inline effective-find-position-test effective-find-position-key))
1841 (defun effective-find-position-test (test test-not)
1842   (cond ((and test test-not)
1843          (error "can't specify both :TEST and :TEST-NOT"))
1844         (test (%coerce-callable-to-fun test))
1845         (test-not
1846          ;; (Without DYNAMIC-EXTENT, this is potentially horribly
1847          ;; inefficient, but since the TEST-NOT option is deprecated
1848          ;; anyway, we don't care.)
1849          (complement (%coerce-callable-to-fun test-not)))
1850         (t #'eql)))
1851 (defun effective-find-position-key (key)
1852   (if key
1853       (%coerce-callable-to-fun key)
1854       #'identity))
1855
1856 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
1857 (macrolet (;; shared logic for defining %FIND-POSITION and
1858            ;; %FIND-POSITION-IF in terms of various inlineable cases
1859            ;; of the expression defined in FROB and VECTOR*-FROB
1860            (frobs ()
1861              `(etypecase sequence-arg
1862                 (list (frob sequence-arg from-end))
1863                 (vector 
1864                  (with-array-data ((sequence sequence-arg :offset-var offset)
1865                                    (start start)
1866                                    (end (or end (length sequence-arg))))
1867                    (multiple-value-bind (f p)
1868                        (macrolet ((frob2 () '(if from-end
1869                                                  (frob sequence t)
1870                                                  (frob sequence nil))))
1871                          (typecase sequence
1872                            (simple-vector (frob2))
1873                            (simple-string (frob2))
1874                            (t (vector*-frob sequence))))
1875                      (declare (type (or index null) p))
1876                      (values f (and p (the index (+ p offset))))))))))
1877   (defun %find-position (item sequence-arg from-end start end key test)
1878     (macrolet ((frob (sequence from-end)
1879                  `(%find-position item ,sequence
1880                                   ,from-end start end key test))
1881                (vector*-frob (sequence)
1882                  `(%find-position-vector-macro item ,sequence
1883                                                from-end start end key test)))
1884       (frobs)))
1885   (defun %find-position-if (predicate sequence-arg from-end start end key)
1886     (macrolet ((frob (sequence from-end)
1887                  `(%find-position-if predicate ,sequence
1888                                      ,from-end start end key))
1889                (vector*-frob (sequence)
1890                  `(%find-position-if-vector-macro predicate ,sequence
1891                                                   from-end start end key)))
1892       (frobs)))
1893   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
1894     (macrolet ((frob (sequence from-end)
1895                  `(%find-position-if-not predicate ,sequence
1896                                          ,from-end start end key))
1897                (vector*-frob (sequence)
1898                  `(%find-position-if-not-vector-macro predicate ,sequence
1899                                                   from-end start end key)))
1900       (frobs))))
1901
1902 ;;; the user interface to FIND and POSITION: Get all our ducks in a
1903 ;;; row, then call %FIND-POSITION.
1904 (declaim (inline find position))
1905 (macrolet ((def-find-position (fun-name values-index)
1906              `(defun ,fun-name (item
1907                                 sequence
1908                                 &key
1909                                 from-end
1910                                 (start 0)
1911                                 end
1912                                 key
1913                                 test
1914                                 test-not)
1915                 (nth-value
1916                  ,values-index
1917                  (%find-position item
1918                                  sequence
1919                                  from-end
1920                                  start
1921                                  end
1922                                  (effective-find-position-key key)
1923                                  (effective-find-position-test test
1924                                                                test-not))))))
1925   (def-find-position find 0)
1926   (def-find-position position 1))
1927
1928 ;;; the user interface to FIND-IF and POSITION-IF, entirely analogous
1929 ;;; to the interface to FIND and POSITION
1930 (declaim (inline find-if position-if))
1931 (macrolet ((def-find-position-if (fun-name values-index)
1932              `(defun ,fun-name (predicate sequence
1933                                 &key from-end (start 0) end key)
1934                 (nth-value
1935                  ,values-index
1936                  (%find-position-if (%coerce-callable-to-fun predicate)
1937                                     sequence
1938                                     from-end
1939                                     start
1940                                     end
1941                                     (effective-find-position-key key))))))
1942   
1943   (def-find-position-if find-if 0)
1944   (def-find-position-if position-if 1))
1945
1946 ;;; the deprecated functions FIND-IF-NOT and POSITION-IF-NOT. We
1947 ;;; didn't bother to worry about optimizing them, except note that on
1948 ;;; Sat, Oct 06, 2001 at 04:22:38PM +0100, Christophe Rhodes wrote on
1949 ;;; sbcl-devel
1950 ;;;
1951 ;;;     My understanding is that while the :test-not argument is
1952 ;;;     deprecated in favour of :test (complement #'foo) because of
1953 ;;;     semantic difficulties (what happens if both :test and :test-not
1954 ;;;     are supplied, etc) the -if-not variants, while officially
1955 ;;;     deprecated, would be undeprecated were X3J13 actually to produce
1956 ;;;     a revised standard, as there are perfectly legitimate idiomatic
1957 ;;;     reasons for allowing the -if-not versions equal status,
1958 ;;;     particularly remove-if-not (== filter).
1959 ;;;   
1960 ;;;     This is only an informal understanding, I grant you, but
1961 ;;;     perhaps it's worth optimizing the -if-not versions in the same
1962 ;;;     way as the others?
1963 ;;;
1964 ;;; That sounds reasonable, so if someone wants to submit patches to
1965 ;;; make the -IF-NOT functions compile as efficiently as the
1966 ;;; corresponding -IF variants do, go for it. -- WHN 2001-10-06)
1967 ;;;
1968 ;;; FIXME: Remove uses of these deprecated functions (and of :TEST-NOT
1969 ;;; too) within the implementation of SBCL.
1970 (declaim (inline find-if-not position-if-not))
1971 (macrolet ((def-find-position-if-not (fun-name values-index)
1972              `(defun ,fun-name (predicate sequence
1973                                 &key from-end (start 0) end key)
1974                 (nth-value
1975                  ,values-index
1976                  (%find-position-if-not (%coerce-callable-to-fun predicate)
1977                                         sequence
1978                                         from-end
1979                                         start
1980                                         end
1981                                         (effective-find-position-key key))))))
1982   
1983   (def-find-position-if-not find-if-not 0)
1984   (def-find-position-if-not position-if-not 1))
1985 \f
1986 ;;;; COUNT
1987
1988 (eval-when (:compile-toplevel :execute)
1989
1990 (sb!xc:defmacro vector-count (item sequence)
1991   `(do ((index start (1+ index))
1992         (count 0))
1993        ((= index (the fixnum end)) count)
1994      (declare (fixnum index count))
1995      (if test-not
1996          (unless (funcall test-not ,item
1997                           (apply-key key (aref ,sequence index)))
1998            (setq count (1+ count)))
1999          (when (funcall test ,item (apply-key key (aref ,sequence index)))
2000            (setq count (1+ count))))))
2001
2002 (sb!xc:defmacro list-count (item sequence)
2003   `(do ((sequence (nthcdr start ,sequence))
2004         (index start (1+ index))
2005         (count 0))
2006        ((or (= index (the fixnum end)) (null sequence)) count)
2007      (declare (fixnum index count))
2008      (if test-not
2009          (unless (funcall test-not ,item (apply-key key (pop sequence)))
2010            (setq count (1+ count)))
2011          (when (funcall test ,item (apply-key key (pop sequence)))
2012            (setq count (1+ count))))))
2013
2014 ) ; EVAL-WHEN
2015
2016 (defun count (item sequence &key from-end (test #'eql) test-not (start 0)
2017                 end key)
2018   #!+sb-doc
2019   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2020    which defaults to EQL."
2021   (declare (ignore from-end) (fixnum start))
2022   (let ((end (or end (length sequence))))
2023     (declare (type index end))
2024     (seq-dispatch sequence
2025                   (list-count item sequence)
2026                   (vector-count item sequence))))
2027 \f
2028 ;;;; COUNT-IF and COUNT-IF-NOT
2029
2030 (eval-when (:compile-toplevel :execute)
2031
2032 (sb!xc:defmacro vector-count-if (predicate sequence)
2033   `(do ((index start (1+ index))
2034         (count 0))
2035        ((= index (the fixnum end)) count)
2036      (declare (fixnum index count))
2037      (if (funcall ,predicate (apply-key key (aref ,sequence index)))
2038          (setq count (1+ count)))))
2039
2040 (sb!xc:defmacro list-count-if (predicate sequence)
2041   `(do ((sequence (nthcdr start ,sequence))
2042         (index start (1+ index))
2043         (count 0))
2044        ((or (= index (the fixnum end)) (null sequence)) count)
2045      (declare (fixnum index count))
2046      (if (funcall ,predicate (apply-key key (pop sequence)))
2047          (setq count (1+ count)))))
2048
2049 ) ; EVAL-WHEN
2050
2051 (defun count-if (test sequence &key from-end (start 0) end key)
2052   #!+sb-doc
2053   "Return the number of elements in SEQUENCE satisfying TEST(el)."
2054   (declare (ignore from-end) (fixnum start))
2055   (let ((end (or end (length sequence))))
2056     (declare (type index end))
2057     (seq-dispatch sequence
2058                   (list-count-if test sequence)
2059                   (vector-count-if test sequence))))
2060
2061 (eval-when (:compile-toplevel :execute)
2062
2063 (sb!xc:defmacro vector-count-if-not (predicate sequence)
2064   `(do ((index start (1+ index))
2065         (count 0))
2066        ((= index (the fixnum end)) count)
2067      (declare (fixnum index count))
2068      (if (not (funcall ,predicate (apply-key key (aref ,sequence index))))
2069          (setq count (1+ count)))))
2070
2071 (sb!xc:defmacro list-count-if-not (predicate sequence)
2072   `(do ((sequence (nthcdr start ,sequence))
2073         (index start (1+ index))
2074         (count 0))
2075        ((or (= index (the fixnum end)) (null sequence)) count)
2076      (declare (fixnum index count))
2077      (if (not (funcall ,predicate (apply-key key (pop sequence))))
2078          (setq count (1+ count)))))
2079
2080 ) ; EVAL-WHEN
2081
2082 (defun count-if-not (test sequence &key from-end (start 0) end key)
2083   #!+sb-doc
2084   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2085   (declare (ignore from-end) (fixnum start))
2086   (let ((end (or end (length sequence))))
2087     (declare (type index end))
2088     (seq-dispatch sequence
2089                   (list-count-if-not test sequence)
2090                   (vector-count-if-not test sequence))))
2091 \f
2092 ;;;; MISMATCH
2093
2094 (eval-when (:compile-toplevel :execute)
2095
2096 (sb!xc:defmacro match-vars (&rest body)
2097   `(let ((inc (if from-end -1 1))
2098          (start1 (if from-end (1- (the fixnum end1)) start1))
2099          (start2 (if from-end (1- (the fixnum end2)) start2))
2100          (end1 (if from-end (1- (the fixnum start1)) end1))
2101          (end2 (if from-end (1- (the fixnum start2)) end2)))
2102      (declare (fixnum inc start1 start2 end1 end2))
2103      ,@body))
2104
2105 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2106   (declare (ignore end)) ;; ### Should END be used below?
2107   `(let ((,sequence (if from-end
2108                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2109                                 (reverse (the list ,sequence)))
2110                         (nthcdr ,start ,sequence))))
2111      (declare (type list ,sequence))
2112      ,@body))
2113
2114 ) ; EVAL-WHEN
2115
2116 (eval-when (:compile-toplevel :execute)
2117
2118 (sb!xc:defmacro if-mismatch (elt1 elt2)
2119   `(cond ((= (the fixnum index1) (the fixnum end1))
2120           (return (if (= (the fixnum index2) (the fixnum end2))
2121                       nil
2122                       (if from-end
2123                           (1+ (the fixnum index1))
2124                           (the fixnum index1)))))
2125          ((= (the fixnum index2) (the fixnum end2))
2126           (return (if from-end (1+ (the fixnum index1)) index1)))
2127          (test-not
2128           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2129               (return (if from-end (1+ (the fixnum index1)) index1))))
2130          (t (if (not (funcall test (apply-key key ,elt1)
2131                               (apply-key key ,elt2)))
2132                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2133
2134 (sb!xc:defmacro mumble-mumble-mismatch ()
2135   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2136         (index2 start2 (+ index2 (the fixnum inc))))
2137        (())
2138      (declare (fixnum index1 index2))
2139      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2140
2141 (sb!xc:defmacro mumble-list-mismatch ()
2142   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2143         (index2 start2 (+ index2 (the fixnum inc))))
2144        (())
2145      (declare (fixnum index1 index2))
2146      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2147 \f
2148 (sb!xc:defmacro list-mumble-mismatch ()
2149   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2150         (index2 start2 (+ index2 (the fixnum inc))))
2151        (())
2152      (declare (fixnum index1 index2))
2153      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2154
2155 (sb!xc:defmacro list-list-mismatch ()
2156   `(do ((sequence1 sequence1)
2157         (sequence2 sequence2)
2158         (index1 start1 (+ index1 (the fixnum inc)))
2159         (index2 start2 (+ index2 (the fixnum inc))))
2160        (())
2161      (declare (fixnum index1 index2))
2162      (if-mismatch (pop sequence1) (pop sequence2))))
2163
2164 ) ; EVAL-WHEN
2165
2166 (defun mismatch (sequence1 sequence2 &key from-end (test #'eql) test-not
2167                            (start1 0) end1 (start2 0) end2 key)
2168   #!+sb-doc
2169   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2170    element-wise. If they are of equal length and match in every element, the
2171    result is Nil. Otherwise, the result is a non-negative integer, the index
2172    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2173    if one is shorter than and a matching prefix of the other, the index within
2174    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2175    :FROM-END argument is given, then one plus the index of the rightmost
2176    position in which the sequences differ is returned."
2177   (declare (fixnum start1 start2))
2178   (let* ((length1 (length sequence1))
2179          (end1 (or end1 length1))
2180          (length2 (length sequence2))
2181          (end2 (or end2 length2)))
2182     (declare (type index length1 end1 length2 end2))
2183     (match-vars
2184      (seq-dispatch sequence1
2185        (matchify-list (sequence1 start1 length1 end1)
2186          (seq-dispatch sequence2
2187            (matchify-list (sequence2 start2 length2 end2)
2188              (list-list-mismatch))
2189            (list-mumble-mismatch)))
2190        (seq-dispatch sequence2
2191          (matchify-list (sequence2 start2 length2 end2)
2192            (mumble-list-mismatch))
2193          (mumble-mumble-mismatch))))))
2194 \f
2195 ;;; search comparison functions
2196
2197 (eval-when (:compile-toplevel :execute)
2198
2199 ;;; Compare two elements and return if they don't match.
2200 (sb!xc:defmacro compare-elements (elt1 elt2)
2201   `(if test-not
2202        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2203            (return nil)
2204            t)
2205        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2206            (return nil)
2207            t)))
2208
2209 (sb!xc:defmacro search-compare-list-list (main sub)
2210   `(do ((main ,main (cdr main))
2211         (jndex start1 (1+ jndex))
2212         (sub (nthcdr start1 ,sub) (cdr sub)))
2213        ((or (null main) (null sub) (= (the fixnum end1) jndex))
2214         t)
2215      (declare (fixnum jndex))
2216      (compare-elements (car main) (car sub))))
2217
2218 (sb!xc:defmacro search-compare-list-vector (main sub)
2219   `(do ((main ,main (cdr main))
2220         (index start1 (1+ index)))
2221        ((or (null main) (= index (the fixnum end1))) t)
2222      (declare (fixnum index))
2223      (compare-elements (car main) (aref ,sub index))))
2224
2225 (sb!xc:defmacro search-compare-vector-list (main sub index)
2226   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2227         (jndex start1 (1+ jndex))
2228         (index ,index (1+ index)))
2229        ((or (= (the fixnum end1) jndex) (null sub)) t)
2230      (declare (fixnum jndex index))
2231      (compare-elements (aref ,main index) (car sub))))
2232
2233 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2234   `(do ((index ,index (1+ index))
2235         (sub-index start1 (1+ sub-index)))
2236        ((= sub-index (the fixnum end1)) t)
2237      (declare (fixnum sub-index index))
2238      (compare-elements (aref ,main index) (aref ,sub sub-index))))
2239
2240 (sb!xc:defmacro search-compare (main-type main sub index)
2241   (if (eq main-type 'list)
2242       `(seq-dispatch ,sub
2243                      (search-compare-list-list ,main ,sub)
2244                      (search-compare-list-vector ,main ,sub))
2245       `(seq-dispatch ,sub
2246                      (search-compare-vector-list ,main ,sub ,index)
2247                      (search-compare-vector-vector ,main ,sub ,index))))
2248
2249 ) ; EVAL-WHEN
2250 \f
2251 ;;;; SEARCH
2252
2253 (eval-when (:compile-toplevel :execute)
2254
2255 (sb!xc:defmacro list-search (main sub)
2256   `(do ((main (nthcdr start2 ,main) (cdr main))
2257         (index2 start2 (1+ index2))
2258         (terminus (- (the fixnum end2)
2259                      (the fixnum (- (the fixnum end1)
2260                                     (the fixnum start1)))))
2261         (last-match ()))
2262        ((> index2 terminus) last-match)
2263      (declare (fixnum index2 terminus))
2264      (if (search-compare list main ,sub index2)
2265          (if from-end
2266              (setq last-match index2)
2267              (return index2)))))
2268
2269 (sb!xc:defmacro vector-search (main sub)
2270   `(do ((index2 start2 (1+ index2))
2271         (terminus (- (the fixnum end2)
2272                      (the fixnum (- (the fixnum end1)
2273                                     (the fixnum start1)))))
2274         (last-match ()))
2275        ((> index2 terminus) last-match)
2276      (declare (fixnum index2 terminus))
2277      (if (search-compare vector ,main ,sub index2)
2278          (if from-end
2279              (setq last-match index2)
2280              (return index2)))))
2281
2282 ) ; EVAL-WHEN
2283
2284 (defun search (sequence1 sequence2 &key from-end (test #'eql) test-not
2285                 (start1 0) end1 (start2 0) end2 key)
2286   (declare (fixnum start1 start2))
2287   (let ((end1 (or end1 (length sequence1)))
2288         (end2 (or end2 (length sequence2))))
2289     (seq-dispatch sequence2
2290                   (list-search sequence2 sequence1)
2291                   (vector-search sequence2 sequence1))))