listfindschemeelement

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?

In Scheme, I have this:

(define map-index-pred
  (lambda (pred? f l)
    (foldr
      (lambda (x y)
        (if (pred? x) 
          (cons (f x) y) 
          (cons x y)))
      '() l))) 

(map-index-pred odd? sqr '(2 3 4 5))
(map-index-pred (lambda(i) (< i 2))
                - '(1 2 3 4 5)) 

it works only for the numbers (x), I need it for their indexes...


Solution

  • 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)))