Iterating In Lisp

Joe Marshall has an interesting post on iteration for all you Lisp heads. It’s mostly aimed at Common Lisp and Scheme but a lot of it applies to Elisp as well so even Emacs users will be interested. The mail problem for Elisp is that tail recursion isn’t supported.

I almost always prefer tail recursion for explicit iteration when it’s available but Marshall shows that it’s often better to use one of the built-in functions or mechanisms rather than an explicit loop. For example, the map and reduce functions are a form of implicit iteration that are concise and easy to use.

There are also the more imperative looping mechanisms such as the do, dolist, and dotimes macros that emulate the looping mechanisms in imperative languages. I use these a lot if only for their convenience and the knowledge that their implementations will probably expand into the most efficient code possible. In the absence of tail recursion, they’re a good choice.

Finally, there is the series suit. I’ve never used these so I don’t have any firsthand experience with them. See Marshall’s post for an explanation. You can think of them as a refinement of Map/Reduce that does away with the generation of intermediate lists.

Marshall also mentions the loop macro. Lispers either love it or hate. He, like me, isn’t a fan for all the usual reasons.

If you like any of the various Lisp languages, take a look at Marshall’s post. You’ll enjoy it.

This entry was posted in General and tagged , . Bookmark the permalink.