An index function for strings in emacs-lisp

| categories: emacs-lisp | tags:

I could not find an index function for strings in emacs-lisp. The position function seems to work for numbers, but not strings. Here is a version that works on strings.

(defun index (item list)
  "return index of item in list or nil"
  (let ((counter 0)
        (found nil))
    (dolist (listelement list counter)
      (if (string= item listelement)
          (setq found t)
          (return counter)) ; exit the loop
        ;; else increment counter
        (incf counter)))
    ;; if we found it return counter otherwise return nil
    (if found counter nil)))

Here are some example uses:

(index "test" '("a" "test" "y"))
(index "z" '("a" "b" "z"))
(index "testy" '("a" "test" "y"))

This raises an error because we use string=.

(index 1 '("a" "test" "y" 1))

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

Discuss on Twitter