Kaz Kylheku
11/16/2015 7:59:00 PM
On 2015-11-16, james <dinglei2008@gmail.com> wrote:
> Any faster way to iterate list from end?
>
> (defun print-from-end (lst)
The naming convention LST is not required in Common Lisp. A local variable
named LIST doesn't shadow the LIST function.
> (loop for i from (1- (length lst)) downto 0
> do (nth i lst)))
Yes; construct a reversed copy of the list with the reverse
function, and traverse it forward:
(loop for elem in (reverse list) do ...)
If this list is encapsulated in some object, it may be possible to
keep two lists in parallel, so that both orders are available.
Or you can cache the reversal so that if the reverse order is needed multiple
times, without any updates of the original list in between, it can be reused.
> CL-USER> (time (print-from-end (make-list 100000 :initial-element 'a)))
Timing this is almost pointless. A very basic background in CS, that
every programmer should have, will tell you that what you're doing is slow
*asymptotically*: the running time is O(n*n), meaning that it rises with the
square of the input size. Whenever you double the input size, the time
increases four-fold (except for small input sizes, where the effects of
exceeding the thresholds of various levels of caching make the difference
appear even *worse*).