(Lispex)sicp.io
4.4 · 분석과 실행 나누기

한 번 분석하고 계획을 여러 번 실행한다.

분석기는 표현식 데이터를 환경만 받으면 실행할 수 있는 프로시저로 바꿀 수 있습니다.

생각해 볼 질문

환경이 오기 전에 어떤 일을 미리 끝낼 수 있을까요?

  • Turn each expression node into an execution procedure
  • Capture analyzed operand plans in a closure
  • Reuse one plan with multiple environments

analyze walks the expression tree before any variable values are known. It selects each operator and recursively builds a procedure for every operand.

The resulting plan accepts an environment. Running it only looks up variables, runs the stored operand plans, and applies the already selected operator. One analyzed plan can therefore serve many environments.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(begin
  (define (lookup name environment)
    (cdr (assoc name environment)))
  (define (operator-procedure name)
    (cond ((eq? name '+) +)
          ((eq? name '*) *)))
  (define (analyze expression)
    (cond ((number? expression)
           (lambda (environment) expression))
          ((symbol? expression)
           (lambda (environment)
             (lookup expression environment)))
          (else
           (let ((procedure (operator-procedure (car expression)))
                 (argument-plans (map analyze (cdr expression))))
             (lambda (environment)
               (apply procedure
                      (map (lambda (plan) (plan environment))
                           argument-plans)))))))
  (let ((plan (analyze '(+ x (* y 2)))))
    (list (plan '((x . 3) (y . 4)))
          (plan '((x . 5) (y . 10))))))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 837 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    The first program analyzes one expression and returns (11 25) from two environments.

    실행 흐름에서 볼 점

    Separate the initial analyze applications from the later plan applications. The expression structure is traversed once before either environment is supplied.

    직접 해보기

    힌트를 보기 전에 프로그램을 바꿔 보세요.

    Add a third environment where x is 1 and y is 100. Reuse plan without calling analyze again.

    힌트 하나 보기

    Only add another plan application to the final list.