[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,92 +2,146 @@
|
||||
id: wiki-2026-0508-generics-and-polymorphism
|
||||
title: Generics and Polymorphism
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-GEPO-001]
|
||||
aliases: [Parametric Polymorphism, 제네릭]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.97
|
||||
tags: [auto-reinforced, generics, polymorphism, typescript, type-safety, code-reuse, software-Architecture]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [type-system, generics, polymorphism]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: type-system
|
||||
---
|
||||
|
||||
# [[Generics-and-Polymorphism|Generics-and-Polymorphism]]
|
||||
# Generics and Polymorphism
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "유연한 틀, 견고한 타입: 데이터의 구체적인 '값'이 아닌 '형태'를 추상화하여, 하나의 코드가 다양한 타입을 안전하게 수용(Generics)하게 하거나, 같은 이름의 명령이 객체마다 다르게 행동(Polymorphism)하게 만드는 상위 아키텍처 기술."
|
||||
## 매 한 줄
|
||||
> **"매 한 번 작성, 매 여러 type 에 작동"**. 매 parametric polymorphism (generics) + ad-hoc polymorphism (overloading / traits) + subtype polymorphism (inheritance) 의 셋이 modern type system 의 backbone. 2026 시점 TS 5.x conditional types, Rust trait + GAT, Go 1.21+ generics 가 매 mainstream.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
제네릭과 다형성(Generics-and-Polymorphism)은 소프트웨어의 재사용성과 유연성을 극대화하는 프로그래밍 기법입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **Generics**:
|
||||
* **Abstraction**: 함수나 클래스를 정의할 때 타입을 고정하지 않고 '변수(<T>)'로 둠.
|
||||
* **Type Safety**: 런타임이 아닌 컴파일 타임에 타입의 정합성 정책 보장. ([[Reliability|Reliability]]와 연결)
|
||||
2. **Polymorphism**:
|
||||
* **Ad-hoc**: 연산자 오버로딩처럼 이름만 같은 경우.
|
||||
* **Parametric**: 제네릭을 이용해 소스 코드를 바꾸지 않고 다양한 타입 처리.
|
||||
* **Subtype**: 상속을 통해 부모 타입 변수에 자식 객체를 담아 각자의 행동 정책(Overriding) 수행. ([[Technical-Architecture|Technical-Architecture]]와 연결)
|
||||
### 매 polymorphism 의 종류
|
||||
- **Parametric**: type parameter `<T>` — 매 List<T>, Vec<T>, []T.
|
||||
- **Ad-hoc**: overloading, type classes, traits, interfaces with default impl.
|
||||
- **Subtype**: 매 Liskov — Cat extends Animal.
|
||||
- **Row / Structural**: TS object shape, OCaml row polymorphism.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 과도한 추상화 정책이 성능 저하 정책이나 복잡도 정책만 높인다고 우려했으나, 현대 정책은 강력한 타입 추론 정책(Inference)을 지원하는 TS 같은 환경 정책에서 '중복 코드 정책 제거'를 위한 최고의 무기로 인정받음(RL Update).
|
||||
- **정책 변화(RL Update)**: 이제는 단순 타입 공유 정책을 넘어, 복잡한 조건부 타입 정책(Conditional Types)을 활용해 입력 타입 정책에 따라 출력 타입 정책이 지능적으로 변하는 '메타 프로그래밍 정책' 수준으로 진화함. (Custom-ESLint-Rules와 연결)
|
||||
### 매 dispatch
|
||||
- **Static (monomorphization)**: Rust, C++ template — 매 compile-time 에 specialize → zero overhead.
|
||||
- **Dynamic (vtable)**: Java interface, Go interface, Rust dyn Trait — 매 runtime indirection.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Reliability|Reliability]], [[Technical-Architecture|Technical-Architecture]], [[Custom-ESLint-Rules|Custom-ESLint-Rules]], [[TS-Declaration-Files|TS-Declaration-Files]], [[Discriminated-Unions|Discriminated-Unions]], [[Modularity|Modularity]]
|
||||
- **Key Concept**: Parametric Polymorphism.
|
||||
---
|
||||
### 매 응용
|
||||
1. Collection / container 의 reuse.
|
||||
2. Algorithm 의 generic write (sort, map).
|
||||
3. API design 의 type-safe abstraction.
|
||||
4. Dependency injection 의 decoupling.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### TypeScript — generic constraint
|
||||
```ts
|
||||
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
|
||||
return items.map(i => i[key]);
|
||||
}
|
||||
const names = pluck([{ id: 1, name: "Ada" }], "name"); // string[]
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### TS — conditional + infer
|
||||
```ts
|
||||
type ReturnT<F> = F extends (...a: any[]) => infer R ? R : never;
|
||||
type X = ReturnT<() => Promise<number>>; // Promise<number>
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Rust — trait + generic
|
||||
```rust
|
||||
trait Summable: Copy + std::ops::Add<Output = Self> + Default {}
|
||||
impl<T: Copy + std::ops::Add<Output = T> + Default> Summable for T {}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
fn sum<T: Summable>(xs: &[T]) -> T {
|
||||
xs.iter().copied().fold(T::default(), |a, b| a + b)
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Rust — GAT (Generic Associated Type)
|
||||
```rust
|
||||
trait LendingIterator {
|
||||
type Item<'a> where Self: 'a;
|
||||
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Rust — dyn vs impl Trait
|
||||
```rust
|
||||
fn make_static() -> impl Iterator<Item = i32> { (0..10).filter(|x| x % 2 == 0) } // monomorphized
|
||||
fn make_dyn() -> Box<dyn Iterator<Item = i32>> { Box::new(0..10) } // vtable
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Go — generics (1.21+)
|
||||
```go
|
||||
type Number interface { ~int | ~int64 | ~float64 }
|
||||
|
||||
func Sum[T Number](xs []T) T {
|
||||
var total T
|
||||
for _, x := range xs { total += x }
|
||||
return total
|
||||
}
|
||||
```
|
||||
|
||||
### Java — bounded wildcard (PECS)
|
||||
```java
|
||||
// Producer Extends, Consumer Super
|
||||
static double sum(List<? extends Number> xs) {
|
||||
double s = 0; for (Number n : xs) s += n.doubleValue(); return s;
|
||||
}
|
||||
static void fillWithOnes(List<? super Integer> xs) { xs.add(1); }
|
||||
```
|
||||
|
||||
### Haskell — type class (ad-hoc)
|
||||
```haskell
|
||||
class Eq a where
|
||||
(==) :: a -> a -> Bool
|
||||
instance Eq Int where x == y = primEqInt x y
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Container reuse | parametric `<T>` |
|
||||
| Multiple impl 의 한 interface | trait / interface |
|
||||
| Hot path, type set 작음 | monomorphization (Rust, C++ template) |
|
||||
| Heterogeneous collection | dyn Trait / interface{} / Box<dyn> |
|
||||
| Known finite variants | sum type (enum / discriminated union) — 매 generic 보다 simple |
|
||||
|
||||
**기본값**: TS / Java 는 generics + interface, Rust 는 generic + trait (static dispatch).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Type Systems]] · [[Polymorphism]]
|
||||
- 변형: [[Subtype Polymorphism]] · [[Ad-hoc Polymorphism]] · [[Row Polymorphism]]
|
||||
- 응용: [[Collections]] · [[Trait Objects]] · [[Higher-Kinded Types]]
|
||||
- Adjacent: [[Variance]] · [[Type Erasure]] · [[Monomorphization]] · [[Sum Types]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: API surface design / type signature 의 reasoning / variance bug 진단.
|
||||
**언제 X**: 매 simple concrete type 만 쓰는 곳에 generic 강제 — 매 over-abstraction.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Generic for one caller**: 매 YAGNI — 매 concrete 부터.
|
||||
- **Unbounded `<T>` 의 남용**: 매 actually 필요한 constraint 누락.
|
||||
- **Variance 무시 (Java)**: `List<Cat>` 을 `List<Animal>` 자리에 — covariance bug.
|
||||
- **dyn Trait everywhere (Rust)**: 매 hot path 에서 vtable cost 누적.
|
||||
- **Type erasure 의 망각 (Java)**: runtime 에 `T` 의 reflection 시도.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Pierce *TAPL* 2002, Rust Reference, TS Handbook 5.x, Go spec 1.21).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — TS/Rust/Go/Java generics + polymorphism 종류 정리 |
|
||||
|
||||
Reference in New Issue
Block a user