Hi,

I'm trying to understand the design of Clojure's collections and one
thing that I find odd is the return of functions operating on sequences.
Like for instance a call such as this will return a lazy-seq and not a
vector:

    (drop 2 [1 2 3 4])

The reason why I find it odd is that data-structures have different
characteristics and one may want to use a vector because it supports
efficient indexing and appending to the end.

Of course, dropping 2 elements like above from a vector is probably
going to have O(n) complexity and thus returning something lazy is more
appropriate. And while there are some operations, like "conj", "pop" and
"peek" that preserve the type, functions such as map and filter also
return lazy-seq. And I worry that the property of the collection you
start with is lost, given that this returns a "cons":

     (conj (filter even? [1 2 3 4 5]) 6)

So lets say that I want to write a generic function that preserves the
type of that collection. Is something like this idiomatic?

     (defn only-evens [coll]
       (into (empty coll) (filter even? coll)))

Thanks,

-- 
Alexandru Nedelcu
www.bionicspirit.com

PGP Public Key:
https://bionicspirit.com/key.aexpk

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to