(Lispex)sicp.io
4.2 · 이름에는 문맥이 필요하다

환경은 기호에 값을 준다.

평가는 표현식의 변수 이름을 그 값에 연결하는 명시적인 환경을 필요로 합니다.

생각해 볼 질문

같은 표현식이 다른 환경에서 다른 값을 만드는 이유는 무엇일까요?

  • Represent bindings as an association list
  • Look up symbols separately from evaluating numbers
  • Pass one environment through every recursive call

lookup searches an association list for a pair whose car is the requested symbol. The cdr of that pair is the value supplied by this environment.

evaluate does not attach one permanent meaning to x or y. It receives an environment with the expression, so the same expression tree can be reused with different bindings.

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

    The first program binds x to 3 and y to 4, then returns 11.

    실행 흐름에서 볼 점

    Find the symbol cases for x and y and the assoc calls that resolve them. Both recursive branches receive the same environment value.

    직접 해보기

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

    Change only the environment so that the first expression returns 25. Keep the quoted expression unchanged.

    힌트 하나 보기

    The expression computes x plus twice y, so many different binding pairs can work.