1

I have difficulty in using keep-indexed with multiple arguments:

Using:

(keep-indexed #(if (= %1 3) %2)  [1 2 3 4 5])

I can get the value with index 3, namely (4).

If the index should be given as an argument, for example for index 3:

(keep-indexed #(if (= %1 ???) %2) 3 [1 2 3 4 5])

How should I modify the ???-part?

1 Answer 1

2

You would need to factor it out as keep-indexed expects a two argument function.

(defn my-nth [index coll] (keep-indexed #(if (= %1 index) %2) coll))

(my-nth 3 [1 2 3 4 5])
;=> (4)

If you are just trying to access by index, then for a vector

(get [1 2 3 4 5] 3) ;=> 4

Or indeed simply

([1 2 3 4 5] 3) ;=> 4 

If you, say wanted the values at index 1 and 3.

(map (partial get [1 2 3 4 5]) [1 3])
;=> (2 4)

Or, if you like

(map [1 2 3 4 5] [1 3])
;=> (2 4)

For a list or sequence type, use nth.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.