Macro Guild Melee Fighters

Lisp Dialect

Common Lisp

Synopsis

True macros are one of Lisp’s most unique and amazing features. In fact, the reason Lispers put up with all those annoying parentheses in their code is that those parentheses enable the awesome Lisp macro system.

image with no caption

True macros allow you to add new functionality to Lisp in a very fundamental way. Experienced Lispers can use macros to make their Lisp compiler/interpreter do their bidding cleanly and elegantly.

How It Kills Bugs

By using macros, an experienced Lisper can minimize code duplication, and better tailor the underlying language to the problem at hand. This leads to cleaner code and fewer bugs.

Example A-2. Example

(defmacro three-way-if (expr a b &rest c)
   (let ((val (gensym)))
       `(let ((,val ,expr))
          (cond ((and (numberp ,val) (zerop ,val)) ,a)
                (,val ,@c)
                (t ,b)))))

Explanation

Lisp macros are so powerful that you can actually write your own if-then command! The code shown here creates a macro called three-way-if that has three branches: one for a nil value , one for a numerical zero value , and one for everything else . For most purposes, a function like this might seem stupid, but if you ever want to write a program that constantly needs to distinguish zeros from nils (or needs to handle some other domain-specific headache), you’ll make your life much easier by writing a macro.

Weakness

Since Lisp macros are so powerful, there is always the danger of programmers abusing them. Overuse of macros can make it hard for other programmers to understand your code.

Macros are discussed in Chapter 16.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.59.198