1

I'm trying to do something like this

(loop for i from 1 to 10
      do (let ((fi (funcall f i)))
           when (> fi 0)
           collect (list i fi)))

f is expensive to compute, so I want to only calculate it once.

This isn't working, so I introduce my fi local variable outside the loop scope:

(let ((fi nil))
  (loop for i from 1 to 10
        do (setf fi (funcall f i))
        when (> fi 0)
        collect (list i fi)))

Is there a way to do this (like the first way) that is completely contained within the loop macro?

1

1 Answer 1

4

Two independent for clauses will do:

(loop for i from 1 to 10
      for fi = (funcall f i)
      when (> fi 0)
      collect (list i fi))

Both iteration clauses will be executed at every iteration. The second one will see each new value of i.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.