Lisp - Macro Characters



Macro characters are special characters which calls specific function or trigger actions during read time by LISP reader. In this chapter, we're going to discuss macro characters in details.

Purpose of Macro Characters

Control the LISP Reader

A LISP reader, is a component which works during read time, it reads the text and transform the text into LISP form (s-expresions). Using macro characters, we can control tranformation of code.

Trigger Read Macro

When LISP reader encounters any macro character, it executes the corresponding "read macro" function. This function can determine how to process the subsequent text.

Macro Characters

Following are some of commonly used macro characters in LISP

  • ( (Left Parenthesis) − Used to initiate start of a list. LISP reader recursively reads subsequent objects until a matching closing parenthesis ) is encountered.

  • ) (Right Parenthesis) − Used to close the list.

  • ' (Single Quote) − A shorthand for quote form.

  • ` (Backquote) − Used for quasiquotation to create complex templates with support for embedded evaluations.

  • , (Comma) − Used with backquote to create an expression which is to be evaluated.

  • ; (Semicolon) − Used to indicate the start of the comment.

  • " (Double Quote) − Used to indicate start of a string literal.

  • # (Hash) − A dispatching character. Used as a prefix for special syntaxes like character literals (#\), for vectors (#) and #. for read evaluation.

  • . (Dot) − Used in dotted lists and with # as #. for read time evaluations.

Setting Macro Character

We can use set-macro-character or set-dispatch-macro-character function to customize the default behavior of a macro character. This capability allows us to provide syntactic extensions to the language.

Modify Read Time Behavior

A macro character is associated with a Read Macro which operates during read time, executed by LISP reader. Using read macros we can customize how a LISP code is evaluated before it is compiled/executed.

Example - Read Macro Usage for Single Quote

main.lisp

(defun single-quote-reader (stream char)
   (declare (ignore char)) 
   (list 'quote (read stream t nil t))) 

(set-macro-character #\' #'single-quote-reader)
(print(get-macro-character #\'))

Output

When you execute the code, it returns the following result −

#<FUNCTION SINGLE-QUOTE-READER (STREAM CHAR)
  (DECLARE (SYSTEM::IN-DEFUN SINGLE-QUOTE-READER) (IGNORE CHAR))
  (BLOCK SINGLE-QUOTE-READER (LIST 'QUOTE (READ STREAM T NIL T)))>
Advertisements