I do not read over or edit the content on this blog. There will be spelling errors, grammatical errors, and run-on sentences that make no sense.

Saturday, August 12, 2006

Common Lisp Loops are Easier Than You Think

Okay - the Common Lisp loop macro is insane. It gives you a crazy amount of flexibility that, as a new Lisp programmer, you really don't care about. In this short article I am going to show you how to write a really simple Lisp loop and show you how much nicer it is than a C-style "for" loop.

So, here is a C-style "for" loop:

in C:


int i;

for (i = 0; i < 10; i++) {
printf("%d\n", i);
}


in PHP:


for ($i = 0; $i < 10; $i++) {
echo $i . "\n";
}


Pretty simple, eh? If you are a C/C++/C#/PHP/Java programmer you probably have written thousands of them. I remember learning the C "for" loop for the first time. I was reading a C book and I saw the loop and it made very little sense. Look at a Common Lisp loop that does the same thing:


(loop for i from 0 to 9
do (format t "~d~%" i))


If you have never seen a C-style "for" loop, what would be easier - a "for" loop or actually telling the program to loop, as does the Lisp program? Some of you might say the C program, but I really think that Lisp is a lot more clear than the C-style loop.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home