--- title: "Ch4: Pattern Matching" tags: [source, SDF] source: "Software Design for Flexibility, Hanson & Sussman (2021)" chapter: 4 updated: 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). 패턴이 매칭되면 귀결을 평가해 매칭된 부분식을 교체. ```scheme (define algebra-1 (rule-simplifier (list (rule '(+ (? a) (+ (? b) (? c))) '(+ (+ ,a ,b) ,c)) ; 결합 법칙 (rule '(* (? b) (? a)) (and (expr 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]]