As mentioned earlier, lisp is incredible at abstracting away small everyday stuff you write over and over. A good example is this way one has to define a local variable in order to make variables sucked into a delegates from the surroundings static in C#. As mentioned briefly in this blog post, one needs to change the loop to read like the following code for it to print 0 to 9 instead of 10 times 9:
foreach (int i in numbers) { int j = i; l.Add(delegate() { System.Console.WriteLine(j); }; }
In lisp one would see that this is a pattern and simply abstract it away like this. As one can see, the macro static-loop is more or less exactly the same as the pattern which luckily made it quite easy to write.
(defmacro static-loop ((i container) &body body) (with-gensyms (j) `(loop for ,j in ,container do (let ((,i ,j)) ,@body))))
The only small trick is the with-gensyms macro which prevents leaking the temporary variable j into the scope of where it will be substituted into. So in that regard the macro is even nicer than rolling your own temp variable hack 🙂
For reference the python example works the same way, but allows one to use the lambda function to redefine variables, although one must note that the static-loop solution is more general in that it will make the loop variable local for the whole scope and not just for one lambda function. Funny thing is that I had originally written it like this, which actually worked, although that means that the closure binding is not only by reference but by name.
I tried writing the macro in boo but I failed. Apparently their macro support is still quite new and there’s close to no examples to draw inspiration from. If anyone could help me out with the solution please mail it to me or even better add it as a comment.