从Racket中选择列表中的元素

huangapple go评论60阅读模式
英文:

Selecting Elements from a List in Racket

问题

我在Racket中有一个函数,它接受一个列表,遍历列表,检查列表中的每个项是否满足条件,并打算输出满足条件的每个项的索引列表。我不能使用 "indexes-of"。

目前,我的设置如下:

(define (function lst)
  (define output empty)
  (for ([i (length lst)])
    (cond
      [(条件) (append output (list i))]
    )
  )
  output
)

这会输出一个空列表。我(认为我)明白原因是什么;append 不会像在Python中那样将其参数附加到变量output上,而是将其参数连接为一个新列表。我不知道如何修复这个问题。再次强调,我正在尝试获取索引,因此重要的是保持它们不变。我已经验证了我的条件函数的正常工作;它确实正确识别每个项,问题在于将它们放入可返回的列表中。

英文:

I have a function in Racket which takes a list, iterates through it, checks each item in the list against a condition, and is intended to output a list of the index of every item for which this condition is true. I cannot use indexes-of.

Currently, my setup is:

(define (function lst)
  (define output empty)
  (for ([i (length lst)])
        (cond
          [(CONDITION) (append output (list i))]
        )
    )
  output
)

This outputs an empty list. I (think I) understand the reason why; append doesn't actually append to the variable output (the way one would expect in, say, Python), rather concatenates its parameters as a new list. I do not know how to fix this. Again, I'm trying to fetch indexes, so it's important those remain intact.

I have verified my condition functions properly; this does correctly identify each item, it's getting it into a returnable list that's the issue at this juncture.

答案1

得分: 1

在Racket中(不同于常规Scheme),列表是不可变的,并且append在两者中始终返回一个新的列表。你正在使用的普通for推导式也不返回任何值。

有很多方法可以实现你想要的,而不使用indexes-of(尽管这是简单的方法)。例如,可以使用for/list#:when子句,仅选择满足CONDITION返回true的元素:

(define (function lst)
  (for/list ([elem (in-list lst)]
             [i (in-naturals)]
             #:when (CONDITION elem))
    i))
英文:

Lists in Racket (Unlike regular Scheme) are immutable, and append in both always returns a fresh list anyways. The plain for comprehension you're using doesn't return any value, either.

There's quite a few ways to do what you want without indexes-of (Though that's the easy way). For example, using for/list with a #:when clause to select just the elements that CONDITION returns true for:

(define (function lst)
  (for/list ([elem (in-list lst)]
             [i (in-naturals)]
             #:when (CONDITION elem))
    i))

huangapple
  • 本文由 发表于 2023年3月1日 08:25:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定