m33lky
m33lky

Reputation: 7275

get array values based on a collection of indices

I'm looking for a generalization of the nth function. There is a nice function in Julia and I'm having trouble finding an equivalent in Clojure:

getindex(A, inds...) Returns a subset of array A as specified by inds, where each ind may be an Int, a Range, or a Vector.

This is related to this question: Clojure Remove item from Vector at a Specified Location

Upvotes: 3

Views: 117

Answers (3)

amalloy
amalloy

Reputation: 91907

map already does what you want. (map v indices) works as intended because a vector can be treated as a function of its indices.

Upvotes: 9

leetwinski
leetwinski

Reputation: 17859

with vectors you could also use select-keys. in some cases it can be quite helpful:

user> (select-keys [:a :b :c :d] [0 1])
{0 :a, 1 :b}

Upvotes: 2

Chris Murphy
Chris Murphy

Reputation: 6509

Does this do what you need:

(defn get-nths [xs ns]
  (for [n ns]
    (nth xs n)))

?

Examples for a vector, a range and one only:

(defn x []
  (vector
    (get-nths [:a :b :c :d :e] [2 4])
    (get-nths [:a :b :c :d :e] (range 3))
    (get-nths [:a :b :c :d :e] [0])))

(x)
;; => [(:c :e) (:a :b :c) (:a)]

Upvotes: 2

Related Questions