(Lispex)sicp.io
4.1 · 언어 안의 평가기

프로그램은 프로그램을 데이터로 읽을 수 있다.

표현식을 리스트와 기호로 나타내면 보통의 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.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(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))))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 519 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    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.