Categories
.net boo Books c# lisp Programming

Finished reading Practical Common Lisp

Finally got through the mighty Practical Common Lisp tome. The style of the book is written in a nice mix of theory and practice (with relevant and good examples). My friend Lau asked me why on earth I would want to read a book on Lisp? A fair question since Lisp is really old, actually measured in computer time it might even be called ancient. But I had two main motivations for reading the book, to become a better programmer and secondly to better understand new language features introduced in languages like Boo and C#. Just look at the new LINQ features in C# 3.0 and specifically this video.

I wholeheartedly recommend this book to anyone interesting in a good programming book.

Categories
boo c# lisp Programming python

The power of lisp part 2

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.