/ Published in: Lisp
This one drove me crazy because of the requirement to return -1 if s not in los.
(list-index s los) returns the zero-based index of the first occurence of s in los, or -1 if there is no occurences of s in los.
Expand |
Embed | Plain Text
(define list-index (lambda (s los) (if (null? los) -1 (if (eq? (car los) s) 0 (if (= (list-index s (cdr los)) -1) -1 (+ 1 (list-index s (cdr los))))))))
Comments
Subscribe to comments
You need to login to post a comment.

Slightly better:
Both versions could result in repeated recursion if los contains s as res has to be fully evaluated in order to determine if it equals -1. A helper function would come in handy. In Clojure:
` (defn list-index ([s los] (list-index 0 s los)) ([i s los] (cond (= (first los) s) i (empty? los) -1 :else (recur (inc i) s (rest los))))) `switch the order of the first two conditional pairs so (empty? los) is checked before (first los)