Find item index in list

I need to get the index of an item in a list in a schema. For instance:

(... 2 '(2 3 4 5))

0

(... 4 '(2 3 4 5))

2

Can anyone help?

+4
source share
7 answers

my final decision:

(define index (lambda (cislo l) (if (equal? (car l) cislo) 0 (+ 1 (index cislo (cdr l)))))) (define map-index-pred (lambda (pred? fl) (foldr (lambda (xy) (if (pred? (index xl)) (cons (fx) y) (cons xy))) '() l))) 
0
source

Something like that

 (define list-index (lambda (e lst) (if (null? lst) -1 (if (eq? (car lst) e) 0 (if (= (list-index e (cdr lst)) -1) -1 (+ 1 (list-index e (cdr lst)))))))) 
+9
source

The following is the clearest solution I could come up with:

 (define (get-list-index l el) (if (null? l) -1 (if (= (car l) el) 0 (let ((result (get-list-index (cdr l) el))) (if (= result -1) -1 (1+ result)))))) 

This solution is basically the same as merriav, except that I added let at the end so that the recursive call is not unnecessarily repeated (in written code or execution).

The decision taken does not seem to contain an empty list or a list that does not contain the item to be searched.

+6
source

You can implement the index using reverse, member, length and cdr as follows:

 (define (index ab) (let [(tail (member a (reverse b)))] (and tail (length (cdr tail)))) 
+3
source

The answer was simpler than you expected, and also without recursion :)

Simple function if you are sure that the item is in the list

 (define element-index (lambda (elemento lista) (- (length lista) (length (memv elemento lista))))) 

If you are considering a case where an item may not be in the list. Return false if not found

 (define element-index (lambda (elemento lista) (if (eqv? (list? (memv elemento lista)) #t) (- (length lista) (length (memv elemento lista))) false ) )) 

Final result:

 > (element-index 2 '(2 3 4 5)) 0 > (element-index 4 '(2 3 4 5)) 2 > (element-index 6 '(2 3 4 5)) false 
0
source

The following code does the trick:

 (define (getpos element lst) (let loop ([counter 0] [temp lst]) (if (= element (car temp)) counter (loop (+ counter 1) (cdr temp))))) 
0
source

Unless you need to worry about the item not being listed, the following code is probably the shortest version. (An exception will occur if an item is not listed.)

 (define (element-index e lst) (cond [(eqv? e (car lst)) 0] [else (+ (element-index e (cdr lst)) 1)]))) 

Otherwise, use the following code:

 (define element-index (letrec ([element-index-helper (lambda (e lst index) (cond [(null? lst) #f] [(eqv? e (car lst)) index] [else (element-index-helper e (cdr lst) (+ index 1))]))]) (lambda (e lst) (element-index-helper e lst 0)))) 

Examples:

 > (element-index 'a '(abc)) 0 > (element-index 'b '(abc)) 1 > (element-index 'c '(abc)) 2 > (element-index 'd '(abc)) #f 
0
source

All Articles