ClojureDocs

导航

命名空间

subvec

clojure.core

自 1.0 起提供 ()
  • (subvec v start)
  • (subvec v start end)
Returns a persistent vector of the items in vector from
start (inclusive) to end (exclusive).  If end is not supplied,
defaults to (count vector). This operation is O(1) and very fast, as
the resulting vector shares structure with the original and no
trimming is done.
4 Examples
;; not supplying 'end' returns vector from 'start' to (count vector)
user=> (subvec [1 2 3 4 5 6 7] 2)
[3 4 5 6 7]

;; supplying 'end' returns vector from 'start' to element (- end 1)
user=> (subvec [1 2 3 4 5 6 7] 2 4)
[3 4]
;; Remove one item by index

(let [coll [0 1 2 3 4 5]
      i 3]
  (concat (subvec coll 0 i)
          (subvec coll (inc i))))
;; => (0 1 2 4 5)
;; To query the indices of a subvec:
(def foo (vec (range 10)))
(def bar (subvec foo 3 7)) 
=> (.start bar)
3
=> (.end bar)
7

;; Increments with repeated slicing:
(def baz (subvec bar 2))
=> (.start baz)
5

;; Return the original vector:
=> (.v bar)
[0 1 2 3 4 5 6 7 8 9]
=> (.v baz)
[0 1 2 3 4 5 6 7 8 9]
;; IndexOutOfBoundsException for bad indices
=> (subvec [0 1 2 3 4 5] 8 9)
Execution error (IndexOutOfBoundsException) at ...
See Also

Creates a new vector containing the args.

Added by alimoeeny

Return true if x implements IPersistentVector

Added by alimoeeny
1 Note
    By , created 7.1 years ago
    ;; Note that subvec holds a reference to the original vector. If you plan 
    ;; to split a large vector and never using it again, consider freeing up
    ;; the reference.
    
    (let [v1 (subvec (vec (range 1e7)) 0 5)
          v2 (subvec (vec (range 1e7)) 5 10)]
          (into v1 v2))
    ;; OutOfMem
    
    (let [v1 (into [] (subvec (vec (range 1e7)) 0 5))
          v2 (into [] (subvec (vec (range 1e7)) 5 10))]
          (into v1 v2))
    ;; [0 1 2 3 4 5 6 7 8 9]