(Lispex)sicp.io
4.7 · 명시적인 대안

첫 성공에서 멈추지 않고 모든 성공을 남긴다.

평가기에서 대안을 데이터로 다루면 모든 유한한 선택을 검사하고 성공한 결과를 모두 반환할 수 있습니다.

생각해 볼 질문

성공 하나 뒤에도 남은 대안을 유지하면 평가가 어떻게 달라질까요?

  • Represent a finite search space as an explicit choice list
  • Evaluate each alternative before applying its requirement
  • Retain every value that satisfies the predicate
  • Enumerate combinations without hiding the search order

The first search receives quoted expression trees. evaluate interprets one tree at a time, while search applies acceptable? to the resulting value and keeps scanning after both failure and success. No early commitment discards the remaining alternatives.

The second program makes two choice positions explicit. scan-y tests every y for one x, and scan-x repeats that work for every x. Returning all pairs whose squared components sum to 25 exposes a finite nondeterministic search as ordinary list-producing control.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(begin
  (define (evaluate expression)
    (if (number? expression)
        expression
        (let ((operator (car expression))
              (left (evaluate (cadr expression)))
              (right (evaluate (caddr expression))))
          (cond ((eq? operator '+) (+ left right))
                ((eq? operator '*) (* left right))))))
  (define (search alternatives acceptable?)
    (if (null? alternatives)
        '()
        (let ((value (evaluate (car alternatives))))
          (if (acceptable? value)
              (cons value (search (cdr alternatives) acceptable?))
              (search (cdr alternatives) acceptable?)))))
  (search '((+ 1 2) (* 2 3) (+ 4 5) (* 4 4)) odd?))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 686 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    The first program returns (3 9). The second returns ((3 4) (4 3)).

    실행 흐름에서 볼 점

    In the first run, follow evaluate before each predicate decision and confirm that success still recurses over the remaining alternatives. In the second run, follow the nested choice order from (1 1) through (4 4) and locate both accepted pairs.

    직접 해보기

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

    Change the first predicate to even? and predict every retained value in the original alternative order.

    힌트 하나 보기

    Evaluate all four expression trees first. A successful value does not stop the scan.