Search code examples
lispschemeracket

How do I find the index of an element in a list in Racket?


This is trivial implement of course, but I feel there is certainly something built in to Racket that does this. Am I correct in that intuition, and if so, what is the function?


Solution

  • Strangely, there isn't a built-in procedure in Racket for finding the 0-based index of an element in a list (the opposite procedure does exist, it's called list-ref). However, it's not hard to implement efficiently:

    (define (index-of lst ele)
      (let loop ((lst lst)
                 (idx 0))
        (cond ((empty? lst) #f)
              ((equal? (first lst) ele) idx)
              (else (loop (rest lst) (add1 idx))))))
    

    But there is a similar procedure in srfi/1, it's called list-index and you can get the desired effect by passing the right parameters:

    (require srfi/1)
    
    (list-index (curry equal? 3) '(1 2 3 4 5))
    => 2
    
    (list-index (curry equal? 6) '(1 2 3 4 5))
    => #f
    

    UPDATE

    As of Racket 6.7, index-of is now part of the standard library. Enjoy!