An index function for strings in emacs-lisp

| categories: emacs-lisp | tags: | View Comments

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)
        (progn 
          (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)))
index

Here are some example uses:

(index "test" '("a" "test" "y"))
1
(index "z" '("a" "b" "z"))
2
(index "testy" '("a" "test" "y"))
nil

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

blog comments powered by Disqus