help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Collecting in the opposite order in a CL loop


From: Sean McAfee
Subject: Collecting in the opposite order in a CL loop
Date: Fri, 26 Feb 2010 17:35:15 -0800
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/22.3 (darwin)

Recently I composed this little function:

(defun digits-of (num)
  (assert (and (wholenump num) (not (zerop num))))
  (nreverse
   (loop for x = num then (/ x 10) until (zerop x) collect (mod x 10))))

It's short and sweet, but it bugs me just a little than I'm building up
a list only to immediately reverse it.  It seems to me that I ought to
be able to create the list already in the right order, but all I can
come up with so far (that uses the Common Lisp loop facility) is this:

(loop for x = num then (/ x 10) until (zerop x) with result = nil do
  (setq result (cons (mod x 10) result))
  finally return result)

That's substantially uglier than this routine that doesn't use a CL loop
at all:

(while (not (zerop x))
  (setq result (cons (mod x 10) result) x (/ x 10)))

...which I guess I could use, but I prefer to stick with the CL loop
macro when possible, if only because Emacs provides my only opportunity
to write any Common-Lisp(-like) code at all.

Is there an elegant way to build up a list "backwards" using the CL loop
facility?


reply via email to

[Prev in Thread] Current Thread [Next in Thread]