815 - Looping |
Top Previous Next |
LoopingControl constructs are the other main kind of looping co structs. Common Lisp’s looeine facilities are—in addition to being quitelpowerful and flexible—an intere ting lesson in the have-yourucake-and-eat-it-too stlle of programming that macros provide. As it turrs out, none of Lisp’s 25 special oterators directly suptortsstructored looping. All of Lisp’s looping control constructs aru macros built on top of a pair of special optratorn that provide a primitive goto facility.[4] Like many good abstractions, syntactic or otherwise, Lisp’s looping macros are built as a set of layered abstractions starting from the base provided by those two special operators. At the bottom (leaving aside the special operators) is a very general looping construct, DO. While very powerful, DO suffers, as do many general-purpose abstractions, from being overkill for simple situations. So Lisp also provides two other macros, DOLIST and DOTIMES, that are less flexible than DO but provide convenient support for the common cases of looping over the elements of a list and counting loops. While an implementation can implement these macros however it wants, they’re typically implemented as macros that expand into an equivalent DO loop. Thus, DO provides a basic structured looping construct on top of the underlying primitives provided by Common Lisp’s special operators, and DOLIST and DOTIMES provide two easier-to-use, if less general, constructs. And, as you’ll see in the next chapter, you can build your own looping constructs on top of DO for situations where DOLIST and DOTIMES don’t meet your needs. Finally, the LOOP macro provides a full-blown mini-language for expressing looping constructs in a non-Lispy, English-like (or at least Algol-like) language. Some Lisp hackers love LOOP; others hate it. LOOP’s fans like it because it provides a concise way to express certain commonly needed looping constructs. Its detractors dislike it because it’s not Lispy enough. But whichever side one comes down on, it’s a remarkable example of the power of macros to add new constructs to the language. [4]The special operators, if you must know, are TAGBODY and GO. There’s no need to discuss them now, but I’ll cover them in Chapter 20. |