Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

The clojure documentation of split-at states that it takes a collection of elements and returns a vector of two lists, each containing elements greater or smaller than a given index:

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

What I want is this:

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

This is a collection cut into two collections that keep the order of the elements (like vectors), preferably without performance penalties.

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

like image 988
the dude Avatar asked Jan 27 '14 09:01

the dude


1 Answers

If you're working 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]]

As regards to performance, the docs on subvec state:

This operation is O(1) and very fast, as the resulting vector shares structure with the original and no trimming is done.

like image 50
Daniel Neal Avatar answered Oct 01 '22 14:10

Daniel Neal