Re: Iterating over generic sequences.



Pillsy wrote:
What do you use to iterate over a generic sequence (in the manner of
quite a few of the "library" functions like FIND-IF)? The major
possibilities seem to be:

1. Using ELT with LOOP or DOTIMES (which seems needlessly inefficient,
especially for lists). The upside is that it's very simple.

2. Using MAP with the appropriate function. This is what I usually do.
It's a little less clear, and for all I know it really isn't that much
more efficient than the ELT solution.

3. Using something more general with closures and LOOP or DO, like so:

(defun do-stuff-with-sequence (sequence)
(let ((iterator
(etypecase sequence
(list
#'(lambda ()
(pop sequence)))
(vector
(let ((i 0)
(length (length sequence)))
#'(lambda ()
(if (= i length)
nil
(prog1
(aref sequence i)
(incf i)))))))))
(loop
:for elt := (funcall iterator)
:while elt
:do (stuff elt))))

(defgeneric do-stuff-with-sequence (sequence)
(:method ((sequence vector))
(loop for element across sequence
do (stuff element)))
(:method ((sequence list))
(loop for element in sequence
do (stuff element))))


Pascal

--
My website: http://p-cos.net
Common Lisp Document Repository: http://cdr.eurolisp.org
Closer to MOP & ContextL: http://common-lisp.net/project/closer/
.



Relevant Pages

  • Re: clarification
    ... operations (like, say, the concatenation of a sequence of lists, etc) ... 100000 loops, best of 3: 18.8 usec per loop ...
    (comp.lang.python)
  • Functions on generic sequences
    ... sequence: either a list or an array. ... Could compute len and sum at same time ... obvious is that for lists, it traverses things twice, once to find the ... (vector (loop for x across sequence ...
    (comp.lang.lisp)
  • Iterating over generic sequences.
    ... Using ELT with LOOP or DOTIMES (which seems needlessly inefficient, ... (defun do-stuff-with-sequence (sequence) ... code that sets up the ITERATOR closure as function or macro. ...
    (comp.lang.lisp)
  • Re: finding the min or max element of a list
    ... (loop with result = (elt seq start) ... Calling ELT in a loop means that when it ... :initial-value (elt sequence 0))) ...
    (comp.lang.lisp)
  • Re: non destructive operations on lists
    ... on lists. ... (loop for elt in list ... unless (funcall test elt) ...
    (comp.lang.lisp)