简体   繁体   English

过滤带有索引的列表 MIT-scheme

[英]Filtering a list with indexes MIT-scheme

Is there a good way to filter a list using each element and its index in scheme?有没有一种使用方案中的每个元素及其索引来过滤列表的好方法? This is how I'm doing it now, but it seems overly complex这就是我现在的做法,但它似乎过于复杂

(map cdr
     (filter (lambda (index-and-element)
               (filter-proc (car index-and-element) 
                            (cdr index-and-element)))
             (map cons (iota (length l))
                       l)))

Looks perfectly fine to me.对我来说看起来很好。 Except, perhaps you meant map cdr ...除了,也许你的意思是map cdr ...

Personally I like very short variable names whenever possible, so instead of index-and-element I'd just use ie -- they are unimportant, it's just some wiring, so make them as invisible as possible.就我个人而言,我喜欢尽可能短的变量名,所以我只使用ie而不是index-and-element ——它们并不重要,只是一些连线,所以让它们尽可能不可见。

Another possibility is to use (map list...) initially, not (map cons...) , and then inside the lambda to use (apply filter-proc ie) .另一种可能性是最初使用(map list...) ,而不是(map cons...) ,然后在lambda内部使用(apply filter-proc ie) this way filter-proc is called with two arguments, so it can be defined (define (filter-proc idx elt)...) .这样filter-proc用两个 arguments 调用,所以可以定义(define (filter-proc idx elt)...)

And after all that, since it is indeed complex and error-prone to type all this anew each time, we'd just define a higher-order function for this so it is easier to use, like毕竟,由于每次重新输入这些内容确实很复杂且容易出错,因此我们只需为此定义一个高阶 function 以便更易于使用,例如

(define (indexed-filter ipred lst)
   (filter (lambda (ie)
               (apply ipred ie))
           (map list (iota (length lst))
                     lst)))

;; (define (ipred idx elt) ....)  ; returns Bool

and use it whenever the need arises.并在需要时使用

I've intentionally left out the (map cadr...) post-processing step, since you could sometimes want to get the indices of the matching elements instead of the elements themselves.我故意省略了(map cadr...)后处理步骤,因为您有时可能想要获取匹配元素的索引而不是元素本身。 So that would be part of the calling "protocol" so to speak -- whether you're interested in indices, elements, or both, you'd just tweak the call to this general procedure.所以将是调用“协议”的一部分,可以这么说——无论你对索引、元素或两者感兴趣,你只需调整对这个通用过程的调用。

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

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