Categories
boo Books Programming

The power of lisp part 1

Lately I’ve been reading the book Practical Common Lisp. My earlier experience with lisp was at the university where I briefly touched lisp in the form of the Scheme dialect. After having read Paul Grahams excellent Hackers and Painters twice, I thought it would probably be a good idea to see if lisp lived up to the hype. After seeing Practical Common Lisp being recommended by bamboo of boo fame and seeing this google tech talk I was convinced that the book was the best way to see all the wonderful stuff lisp has to offer.

So far I’ve been quite impressed with some of the things one can do in the language in a very elegant way. And I suddenly understand why closures work the way it does in C# and python. The problem with moving stuff from a really dynamic language like lisp to a static language like C# is that not everything fits just as fine and you’ll find yourself wondering why the hell code like this returns 10 times 9 instead of 0 to 9. Another thing is that I often find myself remembering small code idioms that just completely goes away when one can build abstractions so easily. The first example is if you want to break out of a double loop. A situation more often that one would think.

I C# one could write a double loop something like this. Notice the introduction of the found variable which is needed to make sure that the loop doesn’t do needless work. Even with an anonymous function it’s quite ugly (and the same is true for a goto solution :)). In lisp it would look something like this (my first common lisp program :-)). The abstraction is in the block concept and in the generalized return construct return-from.

Edit: Can be simplyfied to this:

(let ((l (list (list 1 2 3 4) (list 5 6 7))))
  (loop named outer for i in l do
	(loop for j in i do
	      (when (= j 3)
		(format t "found value, yeah!")
		(return-from outer)))))

One reply on “The power of lisp part 1”

Comments are closed.