我要创建函数,该函数过滤奇数索引。
(filter-idx '(0 1 2 3 4)) => '(1 3)
(filter-idx '(#\a #\b #\c (0 1))) => '(#\b (0 1))
所以,我这样做是这样,但是它不起作用。
(define (filter-idx xs)
(memf (lambda (x)
(= (remainder x 2) 1))
xs))
答案 0 :(得分:3)
您需要分别处理索引和元素。这是一种方法:
(define (filter-idx xs)
(for/list ([i (range (length xs))] ; iterate over indexes of elements
[x xs] ; iterate over elements of list
#:when (odd? i)) ; filter elements in odd indexes
x)) ; create a list with only the elements that meet the condition
例如:
(filter-idx '(0 1 2 3 4))
=> '(1 3)
(filter-idx '(#\a #\b #\c (0 1)))
=> '(#\b (0 1))