On Dec 13, 4:51 am, levand <luke.vanderh...@gmail.com> wrote:
> So, I'm trying to understand functional programming, particularly as
> it relates to the seq abstraction, and I'm hitting a slight difficulty
> as I'm playing around - something that seems as if it ought to be
> simple, is not.
>
> I'm playing with copying one seq into another. I've found several
> different ways to do it, but the most obvious one, in my opinion, is
> missing.
>
> Here's the straight-up, high performance tail recursive version that
> was my first thought:
>
> (defn copy-seq-r [source]
>   (loop [so-far '() to-go source]
>     (if (nil? to-go)
>       so-far
>       (recur (cons (first to-go) so-far)
>              (rest to-go)))))
>
> The obvious problem with this is that because seqs are last-in first-
> out, this returns the seq in reverse order. Obviously not what we
> wanted. And using (reverse) or consing the (last) is awful for
> performance.
>

We'll this version actually does reverse.  So one way to copy a
sequence could be to (reverse (reverse seq)):

(defn copy-seq (seq)
  (reverse (reverse seq)))

or

(def copy-seq (comp reverse reverse))

But, as mago pointed out, copying persistent structures doesn't make
that much sense.
--~--~---------~--~----~------------~-------~--~----~
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
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