Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure: how to get several items by index out of vector

Tags:

clojure

I am using the following code to extract data by index of [1 2], is there any shorter solution?

(vec (map #(nth ["a" "b" "c"] % ) [1 2]))
like image 775
Daniel Wu Avatar asked Jan 04 '15 12:01

Daniel Wu


2 Answers

mapv maps into a vector, and vectors when applied as functions do index lookup

(mapv ["a" "b" "c"] [1 2])
like image 91
noisesmith Avatar answered Nov 15 '22 10:11

noisesmith


If you want ONLY the first and second index of a vector, there are many ways...

A simple sub vector can be used to persist the first index until the third index.

(subvec ["a" "b" "c"] 1 3)

You can map the vector and apply your vector to the first and second index to return the last two indices as a vector.

(mapv ["a" "b" "c"] [1 2])

Using the thread-last macro, you can take 3 indices and drop the first.

(->> ["a" "b" "c"] (take 3) (drop 1))

If you have a vector defined with n indices, and all you need is the last n indices, drop base 0 to return the last n.

(drop 1 ["a" "b" "c"])
like image 23
Seth Avatar answered Nov 15 '22 09:11

Seth