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

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

Re: Collecting in the opposite order in a CL loop


From: Pascal J. Bourguignon
Subject: Re: Collecting in the opposite order in a CL loop
Date: Sat, 27 Feb 2010 03:42:02 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (darwin)

Sean McAfee <eefacm@gmail.com> writes:

> 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)

Use push instead of setq cons.
Use truncate instead of / for integer division.
Use finally (return ...); finally return is ClTl2, not Common Lisp.

(loop
   with result = '()
   for x = num then (truncate x 10)
   until (zerop x) 
   do (push (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?


Notice that building this list backwards as you want it is wrong:

1234 --> (1 2 3 4)
  34 --> (3 4)

with the most significant digits in the lowest indexes, you cannot use
the list of digits do to anything.



If you kept them in the right order, with least significant digits in
lowest indexes:

1234 --> (4 3 2 1)
  34 --> (4 3)

you can easily implement arithmetic operators, or comparisons, or
whatever you need to do with them.






(defun collect-digits (n)
   (unless (zerop n)
      (cons (mod n 10) (collect-digits (truncate n 10)))))

(collect-digits  1234) --> (4 3 2 1)
(collect-digits -1234) --> (6 7 8 9) ; 10-complement



(defun accumulate-digits (n d)
   (if (zerop n)
      d
      (accumulate-digits (truncate n 10) (cons (mod n 10) d))))

(accumulate-digits  1234 '()) --> (1 2 3 4)
(accumulate-digits -1234 '()) --> (9 8 7 6)  ; 10-complement


-- 
__Pascal Bourguignon__


reply via email to

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