You will predict how a quote changes a call into data.
You will also extract a decision from a list using car and cdr.
Read Reading the Parentheses first. Run each example separately in the Playground to see its result.
Here keep means leave a section heading on its current page.
Compare a call and a quoted list
(+ 2 3)Result
5This calls + with the numbers 2 and 3.
Now add a quote mark.
'(+ 2 3)Result
(+ 2 3)The result is a list with three elements, the symbol + and the numbers 2 and 3.
A symbol is a value that can serve as a name in code.
Here + stays a symbol in the list, so no addition takes place.
The leading ' is shorthand for quote. It returns the following data without
evaluating it as code. Calls and list data share the same parenthesized notation.
Read a decision from a list
(define answer '(decision keep))
(car (cdr answer))Result
keepanswer names a list of two symbols, decision and keep.
The first symbol labels the kind of result. The second records the decision.
For a non-empty list, car returns the first element and cdr returns the remaining list.
Here (cdr answer) returns (keep).
The outer car takes its first element, the symbol keep.
You can use these same list operations to inspect a quoted call such as '(+ 2 3).
A program can also construct lists that represent new program expressions.
Recognize related notation
quote preserves fixed data. To build a list with some computed parts, you can
use quasiquote. These four lines show notation, not a program to run.
'x
`x
,x
,@xs| Notation | Name | Meaning |
|---|---|---|
'x | quote | Keep x as data |
`x | quasiquote | Keep a data template with parts that can be computed |
,x | unquote | Within quasiquote, insert the value of x |
,@xs | unquote-splicing | Within quasiquote, insert the elements of the list xs |
The comma forms are used inside quasiquote.
In this lesson, quote is enough to write each fixed list.
Try this
Predict both elements of the result before running the expression.
(list (+ 1 2) '(+ 1 2))Show answer
The result is (3 (+ 1 2)).
The first argument to list calls + and returns 3.
The second argument is quoted, so it returns the three-element list (+ 1 2).
list puts the two values together.
Explain why (car (cdr answer)) returns a symbol while (cdr answer) returns a list.
Then continue to Data, Conditions, and Decisions
to choose a decision with a condition.