(Lispex)sicp.io
4.8 · 패턴 지향 매칭

프레임은 일관된 패턴 바인딩만 기록한다.

패턴 변수는 처음에는 프레임을 확장하고 다시 나타날 때는 같은 값인지 확인합니다.

생각해 볼 질문

매처는 두 데이터 구조를 걸으며 부분 지식을 어떻게 전달할까요?

  • Represent pattern variables as explicit list data
  • Store variable bindings in an association-list frame
  • Match pair structure recursively from left to right
  • Reject a repeated variable when its value conflicts

The form (? who) represents a pattern variable rather than a literal list. On its first occurrence, extend-if-consistent adds who and the matching datum to the frame. Ordinary symbols and pair structure must match directly.

A later occurrence looks up the existing binding before extending anything. Equal data preserves the frame; conflicting data returns failed, which every remaining recursive step propagates. This is one-way matching with variables in the pattern, not full bidirectional unification or database search.

리스펙스 · SICP 코드SICP에 필요한 Scheme 호환 문법을 리스펙스 SICP 프로필로 실행합니다.
(begin
  (define (variable? pattern)
    (and (pair? pattern) (eq? (car pattern) '?)))
  (define (extend-if-consistent variable value frame)
    (let ((found (assoc (cadr variable) frame)))
      (cond (found
             (if (equal? value (cdr found)) frame 'failed))
            (else
             (cons (cons (cadr variable) value) frame)))))
  (define (pattern-match pattern datum frame)
    (cond ((eq? frame 'failed) 'failed)
          ((variable? pattern)
           (extend-if-consistent pattern datum frame))
          ((and (pair? pattern) (pair? datum))
           (pattern-match
             (cdr pattern)
             (cdr datum)
             (pattern-match (car pattern) (car datum) frame)))
          ((equal? pattern datum) frame)
          (else 'failed)))
  (define frame
    (pattern-match '(parent (? who) (? child))
                   '(parent bob alice)
                   '()))
  (list (cdr (assoc 'who frame))
        (cdr (assoc 'child frame))))
리스펙스 학습용 런타임리스펙스 SICP 프로필 1.0.0
리스펙스 SICP 런타임 불러오는 중
리스펙스 · SICP 코드UTF-8 970 / 1,048,576바이트
예제
결과
출력
진단
보이는 실행 흐름0 / 0 개의 실행 이벤트
    이 브라우저 결과는 리스펙스 바우치나 권한이 아닙니다.wasm —
    예상 관찰

    The first program returns (bob alice). The second returns (apple failed).

    실행 흐름에서 볼 점

    Follow recursive car matching before cdr matching, then locate each frame extension. In the second run, watch the second item lookup preserve the apple frame once and return failed for pear. These traces cover only one-way pattern matching.

    직접 해보기

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

    Change the first pattern to (parent (? person) (? person)). Predict the result for (parent bob alice) before running.

    힌트 하나 보기

    The second occurrence must equal the value stored by the first occurrence.