return index of a value

85 views
Skip to first unread message

Glen Rubin

unread,
Sep 27, 2010, 10:45:14 AM9/27/10
to Clojure
I have a vector of numbers

[0 99 3334 53 2 5 99 2 55 63]

I'd like to find the first index of a particular value. For example
if the value was 99 then I want to return 1, b/c the index of 99 is
1. I can do this with a loop/recur structure comparing each value in
the list to my desired value, however am wondering if there isn't a
built-in for doing so?? thanks again!

Stuart Halloway

unread,
Sep 27, 2010, 11:02:58 AM9/27/10
to clo...@googlegroups.com
Hi Glen,

Finding the *first* index isn't very Clojurish, what you want is to find *all* the indexes, lazily. Then if you want the first one, just call first.

(use '[clojure.contrib.seq-utils :only (positions)])
(positions #{99} [0 99 3334 53 2 5 99 2 55 63])
-> (1 6)

Cheers,
Stu

> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

Michael Gardner

unread,
Sep 27, 2010, 11:06:46 AM9/27/10
to clo...@googlegroups.com


In general, 'some' is used for linear searches. Given a vector 'v':

(some #(and (= 99 (v %)) %) (range 0 (count v)))

This is awkward because you're asking for the index and not the value itself. Index-based array manipulation is not often used in Clojure.

Glen Rubin

unread,
Sep 27, 2010, 1:40:53 PM9/27/10
to Clojure
interesting! thx guys!
Reply all
Reply to author
Forward
0 new messages