Kaz Kylheku
8/4/2015 3:14:00 PM
On 2015-08-04, Jim Newton <jimka.issy@gmail.com> wrote:
> Does anyone know if there is a difference between FOR/= and WITH/= in a LOOP such as the following?
>
> (loop :for x :in data
> :for y := (f x)
> :do ...)
>
> (loop :for x :in data
> :with y := (f x)
> :do ...)
"With" is static: it evaluates the initializing expression once; it is loop's
equivalent of "let".
"For" evaluates the initializing expression on each initialization.
If f has no side effects and x doesn't change, then they are the same.
(Of course, x does change above, so they aren't.)
The for clause also has more syntax attached to it. As you can see you have
the "in" keyword. There is no "with y in data" syntax.
"for = " also has more syntax attached to it, namely a "then clause":
for y = (f x) then (1+ x)
(f x) is the initial value for the first iteration, (1+ x) gives the new
value on subsequent iterations.
Multiple for clauses can combine with "and", which achieves parallel binding.
for x = a then c and
for y = b then d
means that x y take on a b simultaneously, and then c d simultaneously.
If expressions c and d refer to the variables x and y, they both refer
to the previous values. If a and b refer to x and y, they will find those
variables nil.
Without the and, expressions b and d are exposed to the new value of x
stored by the prior for.
Lastly, that brings up scope. I am not sure whether this is true in every
loop implementation, but if you do
with x = x
and there is no binding for x in scope, it is an error. This allows:
(let ((x 42))
(loop with x = x ;; loop's x is initialized to 42
....))
However in
for x = x
the x expression is already under the scope of the x on the left hand side;
it is self-assignment.