Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: index of a value in a list or other collection

Tags:

clojure

How do I get the index of any of the elements on a list of strings as so:

(list "a" "b" "c")

For example, (function "a") would have to return 0, (function "b") 1, (function "c") 2 and so on.

and... will it be better to use any other type of collection if dealing with a very long list of data?

like image 499
logigolf Avatar asked Nov 10 '11 22:11

logigolf


1 Answers

Christian Berg's answer is fine. Also it is possible to just fall back on Java's indexOf method of class String:

(.indexOf (appl­y str (list­ "a" "b" "c"))­ "c")

; => 2

Of course, this will only work with lists (or more general, seqs) of strings (of length 1) or characters.

A more general approach would be:

(defn index-of [e coll] (first (keep-indexed #(if (= e %2) %1) coll)))

More idiomatic would be to lazily return all indexes and only ask for the ones you need:

(defn indexes-of [e coll] (keep-indexed #(if (= e %2) %1) coll)) 

(first (indexes-of "a" (list "a" "a" "b"))) ;; => 0
like image 133
Michiel Borkent Avatar answered Sep 28 '22 07:09

Michiel Borkent