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?
The index() method returns the index of the given element in the list. If the element is not found, a ValueError exception is raised.
How to Find the Index of a List Element in Python. You can use the index() method to find the index of the first element that matches with a given search object. The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.
The indexOf(Object) method of the java. util. ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.
To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With