Expressions Components - SICP Comparison Edition"/>
| Original | Python | |
|
Programmers write programs as text, i.e. sequences of characters, entered in a programming environment or a text editor. To run our evaluator, we need to start with a representation of this program text as a Python value. In section 2.3.1 we introduced strings to represent text. We would like to evaluate programs such as 'size = 2\n5 * size' from section 1.1.2. Unfortunately, such program text does not provide enough structure to the evaluator. In this example, the program parts 'size = 2' and '5 * size' look similar, but carry very different meanings. Abstract syntax functions such as assignment_value_expression would be difficult and error-prone to implement by examining the program text. In this section, we therefore introduce a function parse that translates program text to a tagged-linked-list representation, reminiscent of the tagged data of section 2.4.2. For example, the application of parse to the program string above produces a data structure that reflects the structure of the program: a sequence consisting of an assignment of the value 2 to the name size and a multiplication. parse('size = 2\n5 * size') llist('sequence', llist(llist('assignment', llist('name', 'size'), llist('literal', 2)), llist('binary_operator_combination', '*', llist('literal', 5), llist('name', 'size')))) The syntax functions used by the evaluator access the tagged-linked-list representation produced by parse. |
The evaluator is reminiscent of the symbolic differentiation program discussed in section 2.3.2. Both programs operate on symbolic expressions. data. In both programs, the result of operating on a compound expression an object is determined by operating recursively on the pieces of the expression object and combining the results in a way that depends on the type of the expression. object. In both programs we used data abstraction to decouple the general rules of operation from the details of how expressions the objects are represented. In the differentiation program this meant that the same differentiation procedure function could deal with algebraic expressions in prefix form, in infix form, or in some other form. For the evaluator, this means that the syntax of the language being evaluated is determined solely by the procedures that classify and extract pieces of expressions. the syntax of the language being evaluated is determined solely by parse and the functions that classify and extract pieces of the tagged linked lists produced by parse.
| Original | Python | |
|
|
| Original | Python | |
|
Here is the specification of the syntax of our language:
|
Literal expressions are parsed into tagged linked lists with tag 'literal' and the actual value. \[ \begin{align*} \ll\ \mathit{literal}\textit{-}\mathit{expression}\ \gg & = \texttt{llist('literal', }\mathit{value}\texttt{)} \end{align*} \] where $value$ is the Python value represented by the $literal$-$expression$ string. Here $\ll\ $$literal$-$expression$$\ \gg$ denotes the result of parsing the string $literal$-$expression$. parse('1') llist('literal', 1) parse("'hello world'") llist('literal', 'hello world') parse('None') llist('literal', None) The syntax predicate for literal expressions is is_literal. def is_literal(component): return is_tagged_llist(component, 'literal') It is defined in terms of the function is_tagged_llist, which identifies linked lists that begin with a designated string: def is_tagged_llist(component, the_tag): return is_pair(component) and head(component) == the_tag The second element of the linked list that results from parsing a literal expression is its actual Python value. The selector for retrieving the value is literal_value. def literal_value(component): return head(tail(component)) print(literal_value(parse('None'))) None In the rest of this section, we just list the syntax predicates and selectors, and omit their declarations if they just access the obvious linked list elements. We provide a constructor for literals, which will come in handy: def make_literal(value): return llist('literal', value) The tagged-linked-list representation for names includes the tag 'name' as first element and the string representing the name as second element. \[ \begin{align*} \ll\ \mathit{name}\ \gg & = \texttt{llist('name', }\mathit{symbol}\texttt{)} \end{align*} \] where $symbol$ is a string that contains the characters that make up the $name$ as written in the program. The syntax predicate for names is is_name. The symbol is accessed using the selector symbol_of_name. We provide a constructor for names, to be used by operator_combination_to_application: def make_name(symbol): return llist('name', symbol) We do not need to distinguish between expressions and expression statements. Consequently, parse can ignore the difference between the two kinds of components: \[ \ll\ \mathit{expression}\texttt{;}\ \gg {=} \ll\ \mathit{expression}\ \gg \]
Function applications
are parsed as follows:
Conditional expressions
are parsed as follows:
Lambda expressions
are parsed as follows:
A sequence statement
packages a sequence of statements into a
single statement. A sequence of statements is parsed as follows:[4]
Return statements are parsed as follows: \[ \begin{align*} \ll\ \textbf{return}\ \mathit{expression}\ \gg & = \texttt{llist('return\_statement',}\ \ll\ \mathit{expression}\ \gg \texttt{)} \end{align*} \] The syntax predicate and selector are, respectively, is_return_statement and return_expression. Assignments are parsed as follows: \[ \ll\ \mathit{name}\ \ \texttt{=}\ \ \mathit{expression}\ \gg \ \ = \ \ \texttt{llist('assignment',}\ \ll\;\mathit{name}\;\gg \texttt{, }\ll\;\mathit{expression}\;\gg \texttt{)} \] The syntax predicate is is_assignment and the selectors are assignment_symbol and assignment_value_expression. The symbol is wrapped in a tagged linked list representing the name, and thus assignment_symbol needs to unwrap it. def assignment_symbol(component): return symbol_of_name(head(tail(component))) def assignment_value_expression(component): return head(tail(tail(component)))
A pass statement
is parsed as follows:
Function definitions
are parsed as follows:
|
| Original | Python | |
|
Some special forms in our language can be defined in terms of expressions involving other special forms, rather than being implemented directly. One example is cond, which can be implemented as a nest of if expressions. For example, we can reduce the problem of evaluating the expression (cond ((> x 0) x) ((= x 0) (display 'zero) 0) (else (- x))) to the problem of evaluating the following expression involving if and begin expressions: (if (> x 0) x (if (= x 0) (begin (display 'zero) 0) (- x))) Implementing the evaluation of cond in this way simplifies the evaluator because it reduces the number of special forms for which the evaluation process must be explicitly specified. We include syntax procedures that extract the parts of a condexpression, and a procedure cond->if that transforms cond expressions into if expressions. A case analysis begins with cond and has a list of predicate-action clauses. A clause is an else clause if its predicate is the symbol else.[6] (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else)) (define (cond-predicate clause) (car clause)) (define (cond-actions clause) (cdr clause)) (define (cond->if exp) (expand-clauses (cond-clauses exp))) (define (expand-clauses clauses) (if (null? clauses) 'false ; no else clause (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null? rest) (sequence->exp (cond-actions first)) (error "ELSE clause isn't last - - COND->IF" clauses)) (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest)))))) Expressions (such as cond) that we choose to implement as syntactic transformations are called derived expressions. Let expressions are also derived expressions (see exercise ).[7] |
Some syntactic forms in our language can be defined in terms of components involving other syntactic forms, rather than being implemented directly. One example is operator combination, which evaluate transforms into a function application.
We define
operator combinations in terms of
function applications.
Operator combinations are unary or binary and carry their operator symbol as second element
in the tagged-linked-list representation:
The evaluator uses operator_combination_to_application to transform an operator combination into a function application whose function expression is the name of the operator: def operator_combination_to_application(component): operator = operator_symbol(component) if is_unary_operator_combination(component): return make_application(make_name(operator), llist(first_operand(component))) else: return make_application(make_name(operator), llist(first_operand(component), second_operand(component))) |
| Original | Python | |
There is currently no solution available for this exercise. This textbook adaptation is a community effort. Do consider contributing by providing a solution for this exercise, using a Pull Request in Github.
|
| Original | Python | |
|
There is currently no solution available for this exercise. This textbook adaptation is a community effort. Do consider contributing by providing a solution for this exercise, using a Pull Request in Github.
|
| Original | Python | |
| Recall special forms and and or from section 1.1.6: | Recall from section 1.1.6 that the logical composition operations and and or are syntactic sugar for conditional expressions: The logical conjunction $\mathit{expression}_1$ and $\mathit{expression}_2$ is syntactic sugar for $\mathit{expression}_2$ if $\mathit{expression}_1$ else False, and the logical disjunction $\mathit{expression}_1$ or $\mathit{expression}_2$ is syntactic sugar for True if $\mathit{expression}_1$ else $\mathit{expression}_2$. |
| Original | Python | |
|
They are
parsed as follows:
$\ll\ \mathit{expression}_1\ \ \mathit{logical}\textit{-}\mathit{operation}\ \ \mathit{expression}_2\;\gg \ \ = $ llist('logical_composition', '$logical$-$operation$', $\ll\ $$expression$$_1\;\gg$, $\ll\ $$expression$$_2\;\gg$)where $logical$-$operation$ is and or or. Install and and or as new syntactic forms for the evaluator by defining appropriate syntax functions and evaluation functions eval_and and eval_or. Alternatively, show how to implement and and or as derived components. |
| Original | Python | |
| Scheme allows an additional syntax for cond clauses, (test => recipient) If test evaluates to a true value, then recipient is evaluated. Its value must be a procedure of one argument; this procedure is then invoked on the value of the test, and the result is returned as the value of the cond expression. For example (cond ((assoc 'b '((a 1) (b 2))) => cadr) (else false)) returns 2. Modify the handling of cond so that it supports this extended syntax. |
|
| Original | Python | |
| Original | Python | |
Named letis a variant of let that has the form (let var bindings body) The bindings and body are just as in ordinary let, except that var is bound within body to a procedure whose body is body and whose parameters are the variables in the bindings. Thus, one can repeatedly execute the body by invoking the procedure named var. For example, the iterative Fibonacci procedure (section 1.2.2) can be rewritten using named let as follows: (define (fib n) (let fib-iter ((a 1) (b 0) (count n)) (if (= count 0) b (fib-iter (+ a b) a (- count 1))))) Modify let->combination of exercise to also support named let. |
Python supports
while loops that execute a given
statement repeatedly. Specifically,
while $predicate$: $body$
evaluates the $predicate$, and
if the result is true, evaluates the
$body$
and then evaluates
the whole while loop again.
Once the $predicate$ evaluates
to false, the
while loop terminates.
For example, recall the imperative-style version of the iterative
factorial function from section 3.1.3:
def factorial(n):
product = 1
counter = 1
def iter():
nonlocal product, counter
if counter > n:
return product
else:
product = counter * product
counter = counter + 1
return iter()
return iter()
We can formulate the same algorithm using a while loop as follows:
def factorial(n):
product = 1
counter = 1
while counter <= n:
product = counter * product
counter = counter + 1
return product
While loops are parsed as follows:
|
| Original | Python | |