Hanik
Hanik

Reputation: 105

Get value of symbol without evaluating it

It is possible to get value of the symbol unevaluated like this:

(let ((form '(+ 1 2))) `',form)

This expression evaluates to the following:

'(+ 1 2)

Is there some way to do the same thing but without using backquote?

Upvotes: 2

Views: 339

Answers (3)

coredump
coredump

Reputation: 38809

You can use the longer syntax if you want. Let's see how your form is read and evaluated, step-by-step.

(let ((form '(+ 1 2))) `',form)

Apostrophe is quote:

(let ((form '(+ 1 2))) `(quote ,form))

Backquote/comma (quasiquote) is a shorthand for building data:

(let ((form '(+ 1 2))) (list 'quote form))

Evaluate the let binding, which associates form with its value, literally the list (+ 1 2), inside the lexical environment of this expression:

(list 'quote form)

Te above builds a list made of the quote symbol and the current value bound to form. The above results in a list starting with quote and a sublist, which prints as follows:

(quote (+ 1 2))

... which admits this simpler representation:

'(+ 1 2)

So you can use (list 'quote form) if you prefer, but this is not much different.

Upvotes: 0

Rainer Joswig
Rainer Joswig

Reputation: 139261

(let ((form '(+ 1 2))) `',form)

You ask:

It is possible to get value of the symbol unevaluated...

Actually this not really what it does. By default Common Lisp has local variables using lexical bindings, not symbols having values. Above form computes the value of the variable form, not of the symbol form. The value of form is the list (+ 1 2). With the backquoted quote, you put a list (quote ...) around it. Which gets printed as (QUOTE (+ 1 2)) or '(+ 1 2).

Note that Common Lisp has no way to get from a symbol to the value of a lexical binding. In the source code symbols denote variables, but at runtime we have lexical bindings and not associations from symbols to values.

Upvotes: 0

acelent
acelent

Reputation: 8135

(let ((form '(+ 1 2))) (list 'quote form))

If form is really a constant:

(list 'quote (list '+ '1 '2))

The quotes on 1 and 2 are redundant, since they're literals, but they are informative and are already there in case you replace then with actual expressions.

Upvotes: 1

Related Questions