yonutix
yonutix

Reputation: 2439

Scheme filter but the result list contains indices not values

Is there any easy way to create a kind of filter with the outcome the indices instead of values?

for example:

'(#true #false #true) -> '(0 2)

Upvotes: 0

Views: 235

Answers (3)

Shawn
Shawn

Reputation: 52364

Racket has a function for this (Not sure if it was present when this question was asked) - indexes-where, in racket/list.

Example:

> (indexes-where '(1 2 0 3 0 4) zero?)
'(2 4)

Upvotes: 0

assefamaru
assefamaru

Reputation: 2789

You can create a custom filter procedure that returns a list of indices for elements of a list where a predicate produces a true value, as such:

(define (filtr pred lst)
  (for/list ([i lst]
             [n (in-naturals)]
             #:when (pred i))
    n))

For example,

> (filtr number? '(1 2 3 a b c 8 d 19 e f))
'(0 1 2 6 8)
> (filtr (lambda (x) (and x)) '(#true #false #true))
'(0 2)

Upvotes: 2

Mulan
Mulan

Reputation: 135227

Of course there is a way to do it; there's many ways to do it. Here's one way.

(define (func xs)
  (let loop ((index 0) (xs xs))
    (cond ((empty? xs) empty)
          ((car xs) (cons index (loop (add1 index) (cdr xs))))
          (else (loop (add1 index) (cdr xs))))))

(func '(#true #false #true #false #false #true #true))
;; => '(0 2 5 6)

Upvotes: 0

Related Questions