2

New to Clojure and trying to figure out how to index a sequence without using lots of nexts. For instance say I have the sequence:

(a b c d e f g h)

and I want to incorporate into a function the returning of the 4th item of the sequence. There must be some way besides (next (next (next sequence_name)))? So I could just pass the number 4 to the function (or any other number) and get that item from the sequence. Thanks!

2 Answers 2

3

A few different ways:

(take 1 (drop 3 '(a b c d e f g h))) ;; d

(nth '(a b c d e f g h) 3) ;; d

(nth [a b c d e f g h] 3) ;; d

(nth (vec '(a b c d e f g h)) 3) ;;d

I recommend you become familiar with the sequence manipulation functions in the Clojure Cheat Sheet - it's totally worth it. Clojure's sequence library is extremely rich.

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

5 Comments

Thanks for the fast answers! Was looking around the Clojure Cheat Sheet too I'll have to learn up on more of it. My only problem now is that I need to index a sequence when the sequence is stored as a variable. If I had (a b c d e f g) stored into x I've tried (nth 'x 4) and (nth '(x) 4), etc. doesn't seem to work. Or can you only index sequences directly?
Also tried having "abcdefg" stored as x and then (nth '(seq x) 4) which is also apparently wrong, generating an Index out of bounds exception =/
if it's in a variable you don't need to quote it. just try (nth x 4) and you're done :)
You forgot to quote the vector [a b c d e f g h], so it evaluates to something quite different from the quoted list (a b c d e f g h).
good point. a...h there are just placeholders for the actual values though.
2

good old nth should do the trick

user> (nth '(a b c d e f g h) 4)                                                                                                                                                   
e 

(that is indexed from 0 of course)

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.