I need to get index of element in list in scheme. For example:
(... 2 '(2 3 4 5))
0
(... 4 '(2 3 4 5))
2
Can someone help?
I need to get index of element in list in scheme. For example:
(... 2 '(2 3 4 5))
0
(... 4 '(2 3 4 5))
2
Can someone help?
Somthing like this
(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))))))))
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 largely the same as merriav's except that I've added a let at the end so that the recursive call is not unnecessarily repeated (in written code or execution).
The accepted solution does not seem to account for an empty list, or a list that does not contain the element being sought after.
You could implement index using reverse, member, length, and cdr as follows:
(define (index a b)
(let [(tail (member a (reverse b)))]
(and tail (length (cdr tail))))
my final solution:
(define index
(lambda (cislo l)
(if (equal? (car l) cislo) 0 (+ 1 (index cislo (cdr l))))))
(define map-index-pred
(lambda (pred? f l)
(foldr (lambda (x y)
(if (pred? (index x l))
(cons (f x) y) (cons x y))) '() l)))
The answer was easier than you guys expected, also without recursion :)
Simple function, in case you are sure the element is in the list
(define element-index
(lambda (elemento lista)
(- (length lista) (length (memv elemento lista)))))
If you consider the case where the element 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
The following code achieves the objective :
(define (getpos element lst)
(let loop ([counter 0] [temp lst])
(if (= element (car temp)) counter
(loop (+ counter 1) (cdr temp)))))
If you don't need to worry about the case that the element is not in the list, the following code is probably the shortest version. (An exception will occur if the element is not in the list.)
(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 '(a b c))
0
> (element-index 'b '(a b c))
1
> (element-index 'c '(a b c))
2
> (element-index 'd '(a b c))
#f