Lisp - Uses of Macros



A LISP macro is a very powerful feature of LISP which allows developers to extend the language itself making LISP a metaprogramming language. As compared to function which work on evaluated values, a macro manipulates the code structure before evaluation. In this chapter, we're exploring various areas where a LISP macro plays its crucial role.

Code Transformation

Creating New Syntaxes

A Macro can be used to create entirely new syntactic constructs. Using new constructs, we can tailor the language to specific problem domains. For example in Banking application, +, - can be used to add, deduct amount from account. We can even create custom control flow structures.

Automating Code Genearation Process

Using macro, we can generate code. So we can create repeatitive code to reduce reducdancy and potential errors. It is particularly useful where similar functions are to be created or data structures are to created.

Domain Specific Language, DSL

We can create a Domain Specific Language, DSL using macro. A DSL is a specialized language for a particular application. We can represent complex logics using natural intuitive ways.

Controlling Evaluation of Code

Condition based Evaluation

Using macro we can create custom construct which can act as if, when and unless where certain expressions should be evaluated under specific condition as a macro can control which argument is to be evaluated.

Binding Control

Using macro, we can manipulate lexical bindings. We can introduce new variables and control their scopes via a macro. This feature is crucial to create construct like let

Enhancing Efficiency

Compile Time Optimization

As macros are expanded during compile time, we've opportunity to create more efficient code. Performing computation/transformation at compile time, we can elliminate runtime overhead.

Inline code

As macros can generate inline code so we can elliminate use of functions which reduces runtime overhead.

Conclusion

LISP is a metaprogramming language with a use of macros. Programmers can write code which generate/manipulate other codes.

Advertisements