6

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?

1
  • Can you show the desired results in a specific example?
    – BLUEPIXY
    Nov 10, 2011 at 23:49

9 Answers 9

9

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
4
  • You say instanceOf in the first sentence, instead of indexOf. Nov 11, 2011 at 12:15
  • Also your implementation is a bit fragile because of the concatenation of strings. It breaks down when you try to find the index of "ab" in (list "a" "b" "ab"). It should be 2, but your code would return 0. Nov 11, 2011 at 12:17
  • You are right Christian but a little variation from Michiel code should do the trick on a list of strings: (.indexOf (list "abba" "baab" "cbbc") "baab") => 1. Very nice guys!
    – logigolf
    Nov 11, 2011 at 13:30
  • @logigolf: note that you are now using the indexOf method of clojure.lang.PersistentList and not the one of String: github.com/richhickey/clojure/blob/master/src/jvm/clojure/lang/… Nov 11, 2011 at 22:29
8

I'm not sure I understand your question. Do you want the nth letter of each of the strings in a list? That could be accomplished like this:

(map #(nth % 1) (list "abc" "def" "ghi"))

The result is:

(\b \e \h)

Update

After reading your comment on my initial answer, I assume your question is "How do I find the index (position) of a search string in a list?"

One possibility is to search for the string from the beginning of the list and count all the entries you have to skip:

(defn index-of [item coll]
  (count (take-while (partial not= item) coll)))

Example: (index-of "b" (list "a" "b" "c")) returns 1.

If you have to do a lot of look-ups, it might be more efficient to construct a hash-map of all strings and their indices:

(def my-list (list "a" "b" "c"))
(def index-map (zipmap my-list (range)))
(index-map "b") ;; returns 1

Note that with the above definitions, when there are duplicate entries in the list index-of will return the first index, while index-map will return the last.

5
  • Thanks for your very fast answer. What I am looking for is to get for the nth number of any of the elements of the list passing to the function the element as argument, like (function "a") would have to return 0, (function "b") 1, (function "c") 2 and so on ...
    – logigolf
    Nov 10, 2011 at 23:13
  • Oh, so you want to find the index of a given string in a list? Nov 10, 2011 at 23:16
  • Yes that does it!!! I am starting to navigate the Clojure waters and that helps a lot. Thanks again Christian.
    – logigolf
    Nov 10, 2011 at 23:39
  • 1
    @Christian I think you can use zipmap to avoid the calls to interleave and apply hashmap Nov 11, 2011 at 11:53
  • @Christian The problem with the count approach is that if the item is not in the collection you'll get a number one less than the size of the collection, which is the wrong answer. I've added my solution below (don't seem to be able to format code in a comment!) Jun 16, 2016 at 11:33
4

You can use the Java .indexOf method reliably for strings and vectors, but not for lists. This solution should work for all collections, I think:

(defn index-of 
  "Clojure doesn't have an index-of function. The Java .indexOf method 
  works reliably for vectors and strings, but not for lists. This solution
  works for all three."
  [item coll]
  (let [v (if 
            (or (vector? coll) (string? coll)) 
            coll 
            (apply vector coll))]
    (.indexOf coll item)))
1
  • 1
    I don't get this Clojure people. They are missing the boat just for not defining this kind of things. I suppose the rational behind this is the existence of the .indexOf method. It is so sad, because the language had a great potential.
    – jgomo3
    Apr 3, 2018 at 12:28
1

Do you mean, how do you get the nth element of a list?

For example, if you want to get the 2nd element on the list (with zero-based index):

(nth (list "a" "b" "c") 2)

yields

"c"
1
  • Thanks Julien. No it will be the nth of "a" "b" or "c" on the list.
    – logigolf
    Nov 10, 2011 at 23:00
1

Cat-skinning is fun. Here's a low-level approach.

(defn index-of
  ([item coll]
    (index-of item coll 0))
  ([item coll from-idx]
    (loop [idx from-idx coll (seq (drop from-idx coll))]
      (if coll
        (if (= item (first coll))
          idx
          (recur (inc idx) (next coll)))
        -1))))
1

This is a Lispy answer, I suspect those expert in Clojure could do it better:

(defn position 
    "Returns the position of elt in this list, or nil if not present"
    ([list elt n]
        (cond
            (empty? list) nil
            (= (first list) elt) n
            true (position (rest list) elt (inc n))))
    ([list elt]
        (position list elt 0)))
1
  • That is indeed a lovely Lispy solution, and one which I personally like (I particularly like returning nil instead of -1). However the problem with Clojure is that it suffers from the very limited Java stack, which isn't intended to support recursive functions; so on long lists you're likely to hit out-of-stack exceptions. Jun 16, 2016 at 11:42
0

You seem to want to use the nth function.

From the docs for that function:

clojure.core/nth
([coll index] [coll index not-found])
  Returns the value at the index. get returns nil if index out of
  bounds, nth throws an exception unless not-found is supplied.  nth
  also works for strings, Java arrays, regex Matchers and Lists, and,
  in O(n) time, for sequences.

That last clause means that in practice, nth is slower for elements "farther off" in sequences, with no guarantee to work quicker for collections that in principle support faster access (~ O(n)) to indexed elements. For (clojure) sequences, this makes sense; the clojure seq API is based on the linked-list API and in a linked list, you can only access the nth item by traversing every item before it. Keeping that restriction is what makes concrete list implementations interchangeable with lazy sequences.

Clojure collection access functions are generally designed this way; functions that do have significantly better access times on specific collections have separate names and cannot be used "by accident" on slower collections.

As an example of a collection type that supports fast "random" access to items, clojure vectors are callable; (vector-collection index-number) yields the item at index index-number - and note that clojure seqs are not callable.

1
  • The 'nth' on this context was in reference to the n position of the element on a list and not as the function itself. I appreciate your comments, they will surely help me on taking a decision for the kind of collection that I am going to use.
    – logigolf
    Nov 11, 2011 at 0:32
0

I know this question has been answered a million time but here is a recursive solution that leverages deconstructing.

(defn index-of-coll
  ([coll elm]
   (index-of-coll coll elm 0))
  ([[first & rest :as coll] elm idx]
   (cond (empty? coll) -1
         (= first elm) idx
         :else (recur rest elm (inc idx)))))
0
(defn index-of [item items]
  (or (last (first (filter (fn [x] (= (first x) item))
                           (map list items (range (count items))))))
      -1))

seems to work - but I only have like three items in my list

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.