简体   繁体   English

有没有办法在 mit-scheme 中按索引过滤?

[英]Is there a way to filter by index in mit-scheme?

I'm working through 99 scheme problems and I have a solution for P16 (Drop every N'th element from a list.) using recursion, but I'm trying to practice more functional methods.我正在解决 99 个方案问题,并且我有一个 P16 的解决方案(从列表中删除每个第 N 个元素。)使用递归,但我正在尝试练习更多的功能方法。 Is there a clean way to filter by index in mit-scheme?有没有一种干净的方法可以在 mit-scheme 中按索引过滤?

(display (drop '(a b c d e f g h i j k) 3)))
=> (a b d e g h k)

In Python I could use enumerate:在 Python 中,我可以使用枚举:

import string
lst = list(string.ascii_lowercase[:11])
fltr = filter(lambda item: (item[0]+1)%3, enumerate(lst))
mp = map(lambda item: item[1], fltr)
print(list(mp))
=> ['a', 'b', 'd', 'e', 'g', 'h', 'j', 'k']

or list comprehensions或列出理解

print([value for index, value in enumerate(lst) if (index+1)%3])
=> ['a', 'b', 'd', 'e', 'g', 'h', 'j', 'k']

Thanks!谢谢!

My solution using @Dogbert 's hint about zip .我的解决方案使用@Dogbert 关于zip的提示。

;; P16 (**) Drop every n'th element from a list.                                                         
; Example:                                                                                               
; * (drop '(a b c d e f g h i k) 3)                                                                      
; (a b d e g h k)

(define (drop lst n)
  (map (lambda (x) (cadr x))
       (filter (lambda (x) (not (equal? (modulo (+ 1 (car x)) n) 0)))
               (zip (iota (length lst)) lst))))

(display "P16: (drop '(a b c d e f g h i k) 3)\n")
(display (drop '(a b c d e f g h i k) 3))
(define drop-each-nth
  (lambda (l n)
    ((lambda (s) (s s l (- n 1) (lambda (x) x)))
     (lambda (s l* k ret)
       (cond ((null? l*)
              (ret '()))
             ((zero? k)
              (s s (cdr l*)
                 (- n 1)
                 (lambda (x)
                   (ret x))))
             (else
              (s s (cdr l*)
                 (- k 1)
                 (lambda (x)
                   (ret (cons (car l*) x))))))))))

(drop-each-nth '(a b c d e f g h i j k) 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM