Split vector into vector of vectors in clojure instead of vector lists

The split-at documentation claims that it takes a set of elements and returns a vector of two lists , each of which contains elements larger or smaller than a given index:

(split-at 2 [1 2 3 4 5]) [(1 2) (3 4 5)] 

I want it:

 (split-at' 2 [1 2 3 4 5]) [[1 2] [3 4 5]] 

This is a collection carved into two collections that preserve the order of elements (for example, vectors), preferably without penalties.

What is the usual way to do this and are there any performance optimized ways to do this?

+6
source share
2 answers

If you work exclusively with vectors, one option would be to use subvec .

 (defn split-at' [idx v] [(subvec v 0 idx) (subvec v idx)]) (split-at' 2 [1 2 3 4 5]) ;; => [[1 2] [3 4 5]] 

Regarding performance, docs in subvec state:

This operation is O (1) and is very fast, since the resulting structure of vector stocks with and without the original is trimmed.

+11
source

Why not extend the main function with the "vec" function?

So based on the definition of split-at:

 (defn split-at "Returns a vector of [(take n coll) (drop n coll)]" {:added "1.0" :static true} [n coll] [(take n coll) (drop n coll)]) 

We can add vec to each element of the vector result.

 (defn split-at-vec [n coll] [(vec (take n coll)) (vec (drop n coll))]) 

Freed from β€œperformance penalties,” I think that when you turn your lazy words into a vector, you lose lazy productivity.

+2
source

All Articles