Beautiful Scheme – quote

Scheme is a beautiful language.

— prof Ben Leong

Recently I read some Scheme articles and I find myself start appreciating more about its beauty. I am going to start a series of posts to share my thoughts and problems I had in learning.

Code is data

Any technology sufficiently advanced is indistinguishable from magic.

— Arthur C. Clarke

Programming language interpreter is magic to beginners.

However, writing a scheme interpreter in scheme is surprisingly simple. There are many reasons, but the most important one is probably the fact that scheme code can be naturally represented in scheme list.

The boundary between code and data has been blurring since Von Neumann architecture, and many programming languages like Javascript supports evaluating code in string format at runtime. Scheme went one step further. Any scheme code can be converted to scheme data value with “quote” function.

“quote” function is something that confused me a lot when I learnt scheme. I listed some questions I had and my answers below.

why it is called “quote”?

Think about how you use javascript eval(). You write some JS code, quote them into a string and call eval on the string. It is the same for scheme, except that quoted scheme code is structured data, which is much easier to process.

what does “quote” exactly do?

Converts scheme code into data.

code data
‘123 [integer] 123
‘#t [boolean] #t
‘”hello” [string] “hello”
‘define [symbol] define
‘(1 (2 3)) [list] ([integer] 1, [list]([integer] 2, [integer] 3))
”(1 2) [list] ([symbol] quote, [list]([integer] 1, [integer] 2))

''(1 2) is actually (quote (quote (1 2))), which converts (quote (1 2))into data.

Unlike “” in javascript, you don’t need to escape “quote” inside your code because there is no ambiguity.

why does scheme need “quote”?

Scheme without “quote” is still Turing complete. I think the main reason for introducing “quote” is macros, which makes scheme flexible and extensible.

why do we need symbol?

Symbol seems to be the same as interned string. However, we cannot replace symbol with string because '"define"  and 'define will be not distinguishable.

To make 'define meaningful, a new first class type has to be introduced, and that is symbol. Note that introducing symbol data type does not add any syntax to scheme. 'define is just syntactical sugar for (quote define).

This may sounds hacky, but it worth it because it gives scheme the power to process code in the same way it process lists. We will see more about this in another post about macros.


Leave a Reply

Your email address will not be published. Required fields are marked *