开发者

Conditional anaphoric collection best practices?

开发者 https://www.devze.com 2023-02-08 01:01 出处:网络
I trying to iterate through a sequence, conditionally perform an operation on each element and then collect it 开发者_StackOverflow社区(but only if it matched the criteria). Here is a simplified examp

I trying to iterate through a sequence, conditionally perform an operation on each element and then collect it 开发者_StackOverflow社区(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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号