Posted By

gleather on 01/14/08


Tagged

scheme list-index eopl


Versions (?)

list-index (Scheme)


 / 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.

  1. (define list-index
  2. (lambda (s los)
  3. (if (null? los)
  4. -1
  5. (if (eq? (car los) s)
  6. 0
  7. (if (= (list-index s (cdr los)) -1)
  8. -1
  9. (+ 1 (list-index s (cdr los))))))))

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: the_coder on June 4, 2008

Slightly better:

(define (list-index s los)

  (cond ((null? los) -1)

        ((eq? s (car los)) 0)

        (else

         (let ((res (list-index s (cdr los))))

           (if (= res -1)

               -1

               (+ res 1))))))
Posted By: random_number on December 12, 2009

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)))))  
`
Posted By: random_number on December 13, 2009

switch the order of the first two conditional pairs so (empty? los) is checked before (first los)

You need to login to post a comment.