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: Sean McAfee
Subject: Re: Collecting in the opposite order in a CL loop
Date: Fri, 26 Feb 2010 19:49:54 -0800
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/22.3 (darwin)

pjb@informatimago.com (Pascal J. Bourguignon) writes:

> Sean McAfee <eefacm@gmail.com> writes:
>> (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.

Thanks for the tips.  But what's the reason for the last two?  They seem
equivalent to me, aside from the latter forms having the small advantage
of brevity over the former.

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

Nothing except what I need it for.  I want to transform my input text in
chunks of a certain small unit, identified by a regexp, and to do so a
variable number of units at a time, inserting a space between the
groups.  The basic outline of my code is as follows:

(defun transform-text (arg)
  (interactive "p")
  (save-match-data
    (loop for count in (digits-of arg) do
      (loop repeat count do
        (search-forward-regexp "\\=\\s *\\(etc.etc.\\)")
        (replace-match (compute-replacement-text (match-string 1)))
        finally (insert " "))
      finally (backward-delete-char 1))))

So an argument of 123 to this routine would mean "transform one unit,
insert a space, transform two more units, add a space, and lastly
transform three more units."  I need the digits most-significant-first
because that's the order I typed them in.

Anyway, I like how the collect clause lets me accumulate a return value
for the loop without having to declare one explicitly, and was hoping a
similar construction might let me do the same in the correct order for
this usage.


reply via email to

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