Search code examples
iterationlispcommon-lisp

Lisp, iterating backwards


Is there a way (with loop or iterate, doesn't matter) to iterate over sequence backwards?

Apart from (loop for i downfrom 10 to 1 by 1 do (print i)) which works with indexes, and requires length, or (loop for elt in (reverse seq)) which requires reversing sequence (even worse then the first option).


Solution

  • Iterate can do it:

    (iterate (for x :in-sequence #(1 2 3) :downto 0)
             (princ x))
    ; => 321
    

    As others have noted, this will be very inefficient if used on lists.