On Mon, Aug 17, 2009 at 11:35 PM, Mark Triggs <mark.h.tri...@gmail.com>wrote:

>
> Thanks all.  So combining a few suggested ideas:
>
>  (defn slice
>  "Return the items in coll at index positions keys.
>
>   (slice [0 4 6] \"abcdefg\") => (\\a \\e \\g)"
>    [keys coll]
>    (let [max-idx (apply max keys)
>          keyset (set keys)]
>      (map second
>           (filter (fn [[idx _]] (keyset idx))
>                   (take-while (fn [[idx _]] (<= idx max-idx))
>                               (indexed coll))))))
>
> This version has the advantage of working on infinite sequences and not
> hanging onto the head.  This works as expected:
>
>  (slice [200 201] (repeatedly #(int-array 102400)))
>
> without blowing up the stack or throwing OutOfMemory (on my JVM).


So does the very simple

(defn slice [indices coll]
  (map #(nth coll %) indices))

though that doesn't use keys rather than position with maps.

(defn slice [indices coll]
  (map #(get coll %) indices))

does, but works for maps and vectors but not lists. It does work for
strings.

(defn slice [indices coll]
  (map #(get (indexed coll) %) indices))

should if (indexed coll) has the semantics it seems it should from what
you've posted, but the indexed function is apparently bleeding-edge because
my copy of clojure 1.0 doesn't have anything by that name in it.

(defn slice [coll & indices]
  (map #(nth coll %) indices))

has the same argument syntax as suggested originally by Mark.

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