unofficial mirror of help-gnu-emacs@gnu.org
 help / color / mirror / Atom feed
* Collecting in the opposite order in a CL loop
@ 2010-02-27  1:35 Sean McAfee
  2010-02-27  2:42 ` Pascal J. Bourguignon
  0 siblings, 1 reply; 4+ messages in thread
From: Sean McAfee @ 2010-02-27  1:35 UTC (permalink / raw)
  To: help-gnu-emacs

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?


^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2010-02-27 11:50 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2010-02-27  1:35 Collecting in the opposite order in a CL loop Sean McAfee
2010-02-27  2:42 ` Pascal J. Bourguignon
2010-02-27  3:49   ` Sean McAfee
2010-02-27 11:50     ` Pascal J. Bourguignon

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).