Clojure Goodness: Getting Part Of A Vector With subvec
In Clojure we can get part of a vector collection using the subvec
function. The function takes a vector as argument, a required begin index and optional end index. The returned value is a vector with part of the values of the original vector starting from the begin up to the end index. If we leave out the optional end index, the size of the vector is used as end index.
In the following example we use the subvec
function with and without the end index:
(ns mrhaki.core.subvec
(:require [clojure.test :refer [is]]))
;; Vector of some JVM languages.
(def languages ["Java" "Kotlin" "Clojure" "Groovy"])
;; Using only the start index argumnt we get all items
;; from the start index to the end.
(is (= ["Clojure" "Groovy"] (subvec languages 2)))
;; When we use the start and end index arguments
;; we get the items from start to the given end.
(is (= ["Clojure"] (subvec languages 2 3)))
Written with Clojure 1.10.1.