프로그램은 프로그램을 데이터로 읽을 수 있다.
표현식을 리스트와 기호로 나타내면 보통의 Scheme 프로시저가 그 표현식의 의미를 결정할 수 있습니다.
표현식 데이터를 값으로 바꾸려면 평가기는 무엇을 해야 할까요?
- Distinguish source data from the evaluator executing it
- Dispatch on an operator symbol
- Evaluate a nested expression recursively
The quoted list is data, so the host evaluator does not apply its leading plus symbol. Our evaluate procedure inspects that symbol and chooses the operation itself.
Numbers evaluate directly. A compound expression asks evaluate to interpret both nested operands before combining their values. The evaluator follows the expression tree one node at a time.
(begin
(define (evaluate expression)
(if (number? expression)
expression
(let ((operator (car expression))
(left (cadr expression))
(right (caddr expression)))
(cond ((eq? operator '+)
(+ (evaluate left) (evaluate right)))
((eq? operator '-)
(- (evaluate left) (evaluate right)))
((eq? operator '*)
(* (evaluate left) (evaluate right)))))))
(evaluate '(+ (* 3 4) (- 10 2))))- 출력
- —
- 값
- —
- 진단
- —
The first program interprets the quoted expression and returns 20.
Follow evaluate into the two nested operand trees. Each number reaches the direct-value case, while each list reaches an operator decision.
힌트를 보기 전에 프로그램을 바꿔 보세요.
Add division to the operator cases, then interpret the expression (/ (+ 8 4) 3).
힌트 하나 보기
The new case has the same recursive shape as addition and multiplication.