Lisp - Backquote and Comma



Backquote (`) and Comma (,) are very useful tools in LISP especially while dealing with macros. Using backquote and comma, we can create complex list structures easily.

Backquote (`)

  • Quasi-quotation− A backquote initiates a Quasi-quotation means the expression following the backquote represents a template.

  • Similar to Quote− As regular quote (') symbol prevents evalution. But backquote (`) allows selective evalutation within the template, a quoted expression.

Comma (,)

  • Unquoting− A comma is used to unquote a subexpression within a backquoted expression. The subexpression is evaluated and the result is inserted in the backquoted expression/structure.

  • Escape− A comma essentially provides a way to escape the backquoting effect, in order to insert values in a template.

Comma at (,@)

Comma at (, @) can be used to splice a list into a surrounding list. Elements of list are inserted instead of complete list.

Usage of Backquote and Comma

Backquote and Comma are used together to create an effective template.

  • Backquote to create a template− A backquote creates a template for a List.

  • Comma to evaluate subexpression− Comma instructs to evaluate the sub-expression within template.

  • Insert Result− Sub-expression is evaluated and result in inserted in the template.

Example - Using Backquote and Comma

main.lisp

; create and print a template
(print(let ((x 10)) `(The value of x is ,x)))

Output

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

(THE VALUE OF X IS 10) 

Explanation

  • `(...) − a template is created using backquote.

  • ,x − comma instructs LISP to evaluate x.

  • (The value of x is ,x) − expression is evaluated to a list as .(THE VALUE OF X IS 10)

Example - Using Comma-at (, @)

main.lisp

; create a combined list
(print(let ((my-list '(2 3 4))) `(1 ,@my-list 5)))

Output

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

(1 2 3 4 5) 

Explanation

  • `(...) − a template is created to create a list from 1 to 5 using backquote.

  • ,@my-list − comma-at instructs LISP to splice list and get all elements.

  • (1 ,@my-list 5) − list elements are inserted into template list and a new list (1 2 3 4 5) is returned.

Advertisements