Software Design for Flexibility (Hanson & Sussman 2021) 전문을 wiki/sources/ 아래 챕터별 한국어 wiki 페이지로 컴파일 - SDF-overview: 전체 개요, 챕터 관계도, 공통 테마 - SDF-ch1: 가산적 프로그래밍 철학, 퇴화성, 유연성 비용 - SDF-ch2: 컴비네이터, DSL, 래퍼, 도메인 모델 - SDF-ch3: 제네릭 프로시저, 자동 미분, 트라이 디스패치 - SDF-ch4: 패턴 매칭, 항 재작성, 단일화, 타입 추론 - SDF-ch5: eval/apply, lazy eval, amb, call/cc - SDF-ch6: 레이어드 데이텀/프로시저, 단위 산술, 의존성 추적 - SDF-ch7: 전파 모델, 부분 정보 결합, 의존성 지향 백트래킹 wiki/index.md Sources 섹션 등록, wiki/log.md 기록 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
5.5 KiB
title, tags, source, chapter, updated
| title | tags | source | chapter | updated | ||
|---|---|---|---|---|---|---|
| Ch4: Pattern Matching |
|
Software Design for Flexibility, Hanson & Sussman (2021) | 4 | 2026-04-30 |
Ch4: Pattern Matching
핵심 아이디어
패턴 매칭은 등호 검사의 일반화로, 구조와 내용의 일부를 미지수(패턴 변수)로 남겨둔 채 데이터와 비교하는 기술이다. 이를 통해 항 재작성(term-rewriting) 시스템, 단일화(unification) 기반 타입 추론, **패턴 지향 호출(pattern-directed invocation)**을 구현한다.
주요 개념
4.1 패턴 언어
패턴 구문:
(? a)— 단일 요소 변수(?? t)— 세그먼트 변수 (0개 이상의 연속 요소 매칭)(? a ,number?)— 제약 있는 변수 (number?를 만족하는 요소만 매칭)- 나머지 요소 — 패턴 상수 (정확히 일치)
세그먼트 변수의 중요성: 세그먼트 변수는 매칭 시 탐색이 필요하다. 동일한 패턴 변수가 두 위치에 나타나면 양쪽이 같은 길이여야 한다.
예: 패턴 (a (?? x) (?? y) (?? x) c)는 (a b b b b b b c)를 4가지 방식으로 매칭 가능.
4.2 항 재작성 시스템
규칙(rule): 패턴 + 귀결(consequent). 패턴이 매칭되면 귀결을 평가해 매칭된 부분식을 교체.
(define algebra-1
(rule-simplifier
(list
(rule '(+ (? a) (+ (? b) (? c)))
'(+ (+ ,a ,b) ,c)) ; 결합 법칙
(rule '(* (? b) (? a))
(and (expr<? a b) ; 교환 법칙 (순환 방지)
'(* ,a ,b)))
(rule '(* (? a) (+ (? b) (? c)))
'(+ (* ,a ,b) (* ,a ,c)))))) ; 분배 법칙
rule-simplifier는 고정점(fixed point)에 도달할 때까지 반복 적용하는 단순화기를 반환.
세그먼트 변수를 사용하는 algebra-2: n항 덧셈/곱셈을 직접 표현:
(rule '(+ (?? a) (+ (?? b)) (?? c))
'(+ ,@a ,@b ,@c)) ; 결합 법칙 (n항)
4.2.2 매처 구현
**매처(matcher)**의 인터페이스:
- 인수:
data,dictionary,succeed연속(continuation) - 성공 시
succeed를(새 사전, 소비된 요소 수)로 호출 - 실패 시
#f반환
;; 패턴 상수 매처
(define (match:eqv pattern-constant)
(define (eqv-match data dictionary succeed)
(and (pair? data)
(eqv? (car data) pattern-constant)
(succeed dictionary 1)))
eqv-match)
;; 요소 변수 매처
(define (match:element variable)
(define (element-match data dictionary succeed)
(and (pair? data)
(let ((binding (match:lookup variable dictionary)))
(if binding
(and (equal? (match:binding-value binding)
(car data))
(succeed dictionary 1))
(succeed (match:extend-dict variable
(car data)
dictionary)
1)))))
element-match)
컴파일된 패턴은 이런 매처들의 컴비네이터 조합이다. 세그먼트 변수 매처는 가능한 분할을 백트래킹하며 시도한다.
4.2.4 패턴 지향 호출 (Pattern-Directed Invocation)
패턴 연산자(pattern operator): 입력을 패턴으로 디스패치하여 처리.
(define factorial
(make-pattern-operator
(rule '(0) 1)
(rule '((? n ,positive?))
(* n (factorial (- n 1))))))
attach-rule!로 나중에 규칙을 동적 추가 가능. 컴파일러의 피프홀 최적화처럼, 관련 코드와 규칙을 함께 위치시킬 수 있다.
4.4 단일화 (Unification)
일반 패턴 매칭: 한 쪽은 패턴(변수 포함), 다른 쪽은 데이터.
단일화: 양쪽 모두 변수를 포함할 수 있으며, 두 패턴을 동시에 만족하는 가장 일반적인 변수 할당을 찾는다.
타입 추론 응용: 각 식에서 국소적으로 유추되는 타입 제약들을 단일화로 결합하여 비국소적 타입 제약 도출.
예:
(+ a b)→a: number, b: number를 요구(> a 0)→a: number를 요구- 단일화 결과:
a: number로 확정
4.5 그래프 패턴 매칭
트리(S-표현식)를 넘어 임의의 그래프에 대한 패턴 매칭으로 확장. 체스 이동 규칙을 그래프 패턴으로 표현하는 예시.
핵심 인용
"Pattern matching is a generalization of equality testing. In equality testing we compare two objects to determine that they have the same structure and contents. In pattern matching, we generalize equality testing to allow some parts of the structure and contents to be unspecified."
"A pattern can be matched to a part of a larger datum; the context of the match is unspecified. The ability to work with partial information means that only the specified parts of the pattern are assumptions about the data matched; there are few or no assumptions about the unspecified parts."
"Besides the use of patterns to match data that meets a partial specification, patterns can themselves represent partially known information. Merging such patterns (unification) can generate more specific information than the individual patterns contribute."
관련 개념
- SDF-ch2-dsl — 컴비네이터 패턴으로 매처 구현
- SDF-ch3-generic-procedures — 제네릭 프로시저의 패턴 기반 확장으로서의 패턴 지향 호출
- SDF-ch5-evaluation — 매처를 이용한 언어 구현
- SDF-ch7-propagation — 부분 정보 결합의 다른 형태
- SDF-overview