This article by larrylgq prepared, reproduced please note the Source: http://blog.csdn.net/larrylgq/article/details/7395261
Author: Lu guiqiang
Email: larry.lv.word@gmail.com
Lisp uses special operators to extend the syntax, but the number of special operators in lisp is fixed. To solve this problem, LISP introduces macros, which do not directly do things, but generate actual services.Code.
Evaluate a macro: If the received S-expression is a parameter, a lisp expansion (ecpansion) is returned to evaluate the expansion.
Compilation process: when using compile in clojure to compile the source file, it recursively expands all macros in the file into an extension. In this case, the Code only contains the function call form and special form. Compile the expanded code into a FAS file. The compiled code is executed when the load function is used for loading.
Since macros are not directly evaluated, we can define macros instead of standard format lisp, and each macro can define its own syntax.
Compared with languages defined using the core plus the standard library, LISP can use macros to define new syntaxes and place them in the standard library instead of hard coding at the language core.
Of course, you can also abstract the code that you will reuse into a macro to make the code more concise.
Macro structure: Name + parameter list + optional document string + Declaration + lisp expression body
A simple example is to use macro implementation
(Defmacro while "repeatedly executes body while test expression is true. presumes some side-effect will cause test to become false/nil. returns nil "{: added" 1.0 "} [Test & Body] '(loop [] (when ~ Test ~ @ Body (Recur ))))
When we call it like this:
User => (def A (atom 10) # 'user/auser => (while (POS? @ A) (do (println @ A) (swap! A dec )))
The following code is generated in the compiler:
(Defn while [(POS? A) (do (println @ A) (swap! A dec)]
(Loop [] (
(When (POS? A)
(Do (println @ A) (swap! A dec ))
(Recur)
)
)))
Symbol usage:
Reverse quotation marks: prevent the macro expression from being evaluate.
Tilde: it is used in the back quotes and its value will be replaced.
~ @:
Replace a specific element.