Lisp - Functions vs Macros



LISP is a very powerful and flexible language attributing to support for macros and functions. In this chapter, we'll discussing the differences between functions and macros and when to use them.

Functions

Let's first discuss the behaviour of a function.

Evaluation

A function is evaluated at runtime. This means the arguments of a function are evaluated before calling the function.

A function operates on the values of the arguments passed.

Data Object

A function is first class data object which means a function can be passed as a variable to another function, can be returned from a function and can be stored in a data structure.

Purpose

A function is primarily used to do the computation on the arguments or perform some operation using the arguments.

Macros

A macro can be classified based on below parameters.

Evaluation

A macro is evaluated at compile time. A macro is used for code tramsformation.

A macro works on the actual form of arguments instead of their evaluated values.

When a macro is evaluated by LISP Compiler, it generates a completely new code.

Tranformation

Macro's primary use is to extend LISP. For example, using macros, we can create new control structures or even devise a domain specific language.

Macro helps in automating the code generation.

Control over Evaluation

A macro can control on how and when an argument is to be evaluated. For example, using macros, we can decide −

  • perform conditional evaluation, like to evaluate few arguments based on conditions.

  • perform multiple evaluation, like to evaluate a argument multiple times

  • prevent evaluation, like to ignore a particular argument for evaluation.

Purpose

A macro is primarily used to manipulate the code itself making LISP, a powerful metaprogramming language.

Functions vs Macros

Following table summarizes the key differences.

Feature Functions Macros
Evaluation Runtime Compile Time
Argument Handling Arguments are evaluated before function call Macros works on unevaluated code.
Purpose Functions perform computations. Macros transform code.
When to Use For general purpose computation. To pass as an argument or store in data. to control evalutation of arguments. To extend LISP Syntax. To generate code automatically.

As a summary, we should use functions to work with data and use macros to work with code.

Advertisements