条件照应收集最佳实践?

发布于 2024-10-14 17:27:41 字数 601 浏览 12 评论 0原文

我尝试迭代一个序列,有条件地对每个元素执行操作,然后收集它(但前提是它符合条件)。这是一个有效的简化示例,我只是想知道这在 lisp 中是否正确或最佳实践:

(loop for n in '(1 2 3 4 5)
          when (when (equal (mod n 2) 0) n )
          collect it) 

yields

(2 4)

这有效,它对我来说看起来很有趣,而不是何时-何时,而是因为我觉得我有操纵条件以返回我想要的东西。我知道照应it适用于评估“何时”,但这对我来说似乎有点人为。我错过了什么吗?我成为口齿不清者才几个星期。

编辑:实际上,当我尝试应用这个时,我有点困惑。我真正想做的是:

(loop for n in '(1 2 3 4 5)
        when (when (equal (mod n 2) 0) n)
        collect it
        do (format t "~A" it))

但第二次它似乎变得不受约束......我该怎么做?

I trying to iterate through a sequence, conditionally perform an operation on each element and then collect it (but only if it matched the criteria). Here is a simplified example that works, I just want to know if this is proper or best practice in lisp:

(loop for n in '(1 2 3 4 5)
          when (when (equal (mod n 2) 0) n )
          collect it) 

yields

(2 4)

This works, it just looks funny to me and not so much of the when-when but because I feel like I am having to rig the condition to return what I want. I get that the anaphoric it works on the evaluation of the when but this just seems a little artificial to me. Am I missing something? I have only been a lisper for a few weeks.

Edit: Actually, I am somewhat confused when I tried to apply this. What I really want to do is this:

(loop for n in '(1 2 3 4 5)
        when (when (equal (mod n 2) 0) n)
        collect it
        do (format t "~A" it))

but the second it seems to become unbound... how do I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Spring初心 2024-10-21 17:27:41

我不明白为什么你需要这里照应词。

(loop for n in '(1 2 3 4 5) 
      when (evenp n) 
        collect n and
        do (format t "~A" n))

如果您想要无条件使用 FORMAT,请删除关键字 AND。

I don't see why you need anaphor here.

(loop for n in '(1 2 3 4 5) 
      when (evenp n) 
        collect n and
        do (format t "~A" n))

Delete the keyword AND if you want the FORMAT unconditionally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文