Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of element in list

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?

like image 834
kelly Avatar asked Nov 26 '12 09:11

kelly


People also ask

How do you find the index of a element in Python?

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 do I find the index of a character in a list?

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.

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

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.

How do you call an index from a list in Python?

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.


3 Answers

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))))))))
like image 123
meirrav Avatar answered Nov 03 '22 21:11

meirrav


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.

like image 37
csmith Avatar answered Nov 03 '22 21:11

csmith


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))))
like image 44
wedesoft Avatar answered Nov 03 '22 23:11

wedesoft