Alexander Semenov <bohtva...@gmail.com> writes:

Hi Alexander,

> One can create lazy sequences by wrapping each sequence element inside
> a 'lazy-seq' macro while constructing the sequence. Usually it's done
> with recursion. But what if I need a tail recursive construction of
> the sequence (using recur) accumulating results by appending them to
> the end of an accumulator. It just works using 'conj' and vector until
> 'lazy-seq' is added to the picture. It then breaks append to the end
> vector semantics and the result is now reversed. Here is an example
> (just for illustration - no real world value):

The difference is that conjoining to a list or seq prepends while it
appends for vectors.  The lazy-seq wrapping in your example creates a
(lazy) seq from your vector, so the second-to-nth iteration of your loop
conjoins to a seq and thus prepends.

And there is no sense in having a lazy-seq in a loop-recur, because the
latter is inherently eager.  Your accumulator will be a fully realized
lazy-seq.  That is, the loop-recur defeats the purpose of lazy-seq,
i.e., defer the calculation of values until they are needed.

Although you say the example is only for illustration, it could be
written much more concise (and lazy) like so:

--8<---------------cut here---------------start------------->8---
user> (defn list-set [s n v]
        (concat (take n s) [v] (drop (inc n) s)))
#'user/list-set
user> (list-set [0 1 2 3] 2 :foo)
(0 1 :foo 3)
user> (list-set (list 0 1 2 3) 2 :foo)
(0 1 :foo 3)
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to