在列表中查找元素的索引

kel*_*lly 4 scheme element list

我需要获取方案中列表中元素的索引.例如:

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

0

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

2

有人可以帮忙吗?

mei*_*rav 9

像这样的东西

(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))))))))
Run Code Online (Sandbox Code Playgroud)


csm*_*ith 6

以下是我能想出的最清晰的解决方案:

(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))))))
Run Code Online (Sandbox Code Playgroud)

这个解决方案与merriav大致相同,只是我在最后添加了一个let,这样就不会不必要地重复递归调用(在书面代码或执行中).

接受的解决方案似乎没有考虑空列表,或者不包含所追求的元素的列表.


kel*_*lly -1

我的最终解决方案:

(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)))
Run Code Online (Sandbox Code Playgroud)