Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 363
Alex V Avatar asked Apr 08 '13 04:04

Alex V


People also ask

How do you find the index of an element in a list of lists?

To find the (row, column) index pair of an element in a list of lists, iterate over the rows and their indices using the enumerate() function and use the row. index(x) method to determine the index of element x in the row .

How do I find the index of a specific element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error. To fix this issue, you need to use the in operator.

How do you find the index of a string in a list?

By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string.

What is the index of an element?

Each element inside a list will have a unique position that identifies it. That position is called the element's index.


1 Answers

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!

like image 127
Óscar López Avatar answered Sep 21 '22 02:09

Óscar López