Files
2nd/10_Wiki/Topic_Programming/Architecture/Functional_Programming.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

219 lines
6.4 KiB
Markdown

---
id: wiki-2026-0508-functional-programming
title: Functional Programming
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [FP, Functional Programming, 함수형 프로그래밍]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [paradigm, programming, haskell, scala, rust]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: haskell
framework: multi
---
# Functional Programming
## 매 한 줄
> **"매 function이 first-class — 매 computation은 immutable value 의 transformation"**. 매 FP는 lambda calculus(Church 1936)에서 시작, Haskell/ML/Lisp 통해 academic 으로, 매 React/Redux/Rx 의 mainstream 침투. 2026 mainstream language 모두 FP feature 흡수 (lambdas, map/filter, immutable, pattern match).
## 매 핵심
### 매 Pillars
- **Pure function**: 매 same input → same output, no side effect
- **Immutability**: 매 data 변경 대신 new value 생성
- **First-class function**: 매 function = value (pass, return, store)
- **Referential transparency**: 매 expression을 value로 substitute 가능
- **Higher-order function**: 매 function in/out
### 매 Type system 매력
- **ADT** (algebraic data types): sum (Either, Option) + product (tuple, record)
- **Pattern matching**: 매 exhaustive case analysis
- **Type inference**: 매 Hindley-Milner (ML, Haskell, Rust)
- **Typeclasses** (Haskell) / Traits (Rust) / Type classes (Scala)
### 매 응용
1. React functional components + hooks (modern frontend).
2. Rust iterators + Option/Result (systems FP).
3. Scala/Akka (distributed reactive).
4. Haskell (compilers, finance, formal verification).
5. F# (.NET FP, fintech).
## 💻 패턴
### Haskell — pure + ADT
```haskell
data Tree a = Leaf | Node (Tree a) a (Tree a)
insert :: Ord a => a -> Tree a -> Tree a
insert x Leaf = Node Leaf x Leaf
insert x t@(Node l v r)
| x < v = Node (insert x l) v r
| x > v = Node l v (insert x r)
| otherwise = t
-- 매 IO monad: side effect 격리
main :: IO ()
main = do
putStrLn "Enter name:"
name <- getLine
putStrLn $ "Hello, " ++ name
```
### Rust — iterators + Option
```rust
fn process(nums: Vec<i32>) -> Vec<i32> {
nums.iter()
.filter(|&&x| x > 0)
.map(|&x| x * x)
.take(10)
.collect()
}
// 매 Option chaining (no null)
fn find_user(id: u64) -> Option<String> {
db.get(id)
.and_then(|u| u.email)
.map(|e| e.to_lowercase())
}
```
### Scala — case class + pattern match
```scala
sealed trait Shape
case class Circle(r: Double) extends Shape
case class Rect(w: Double, h: Double) extends Shape
def area(s: Shape): Double = s match {
case Circle(r) => math.Pi * r * r
case Rect(w, h) => w * h
}
// 매 immutable List + fold
val sum = List(1, 2, 3, 4).foldLeft(0)(_ + _)
```
### TypeScript — immutable + HOF
```typescript
// 매 readonly + pipe
const pipe = <T>(...fns: Array<(x: T) => T>) =>
(x: T): T => fns.reduce((v, f) => f(v), x);
const addOne = (n: number) => n + 1;
const double = (n: number) => n * 2;
const pipeline = pipe<number>(addOne, double);
console.log(pipeline(3)); // 8
// 매 Result type (avoid throw)
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
```
### Haskell — Functor / Monad
```haskell
-- 매 Maybe monad: null-safe chain
safeDivide :: Double -> Double -> Maybe Double
safeDivide _ 0 = Nothing
safeDivide x y = Just (x / y)
calc :: Maybe Double
calc = do
a <- safeDivide 10 2
b <- safeDivide a 0 -- 매 short-circuit Nothing
return (b + 1)
-- 매 result: Nothing
```
### Elm — pure UI
```elm
type Msg = Increment | Decrement
type alias Model = { count : Int }
update : Msg -> Model -> Model
update msg model =
case msg of
Increment -> { model | count = model.count + 1 }
Decrement -> { model | count = model.count - 1 }
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, text (String.fromInt model.count)
, button [ onClick Increment ] [ text "+" ]
]
```
### Python — functools (FP-lite)
```python
from functools import reduce, partial, lru_cache
# 매 immutable transform
@lru_cache(maxsize=None)
def fib(n: int) -> int:
return n if n < 2 else fib(n-1) + fib(n-2)
# 매 currying via partial
multiply = lambda x, y: x * y
double = partial(multiply, 2)
print(list(map(double, [1, 2, 3]))) # [2, 4, 6]
# 매 reduce
product = reduce(lambda a, b: a * b, [1, 2, 3, 4], 1)
```
### Persistent data structures (Clojure)
```clojure
(def v [1 2 3])
(def v2 (conj v 4)) ; 매 v unchanged, structural sharing
(println v) ; [1 2 3]
(println v2) ; [1 2 3 4]
;; 매 transducer (composable transformation)
(def xform (comp (filter odd?) (map #(* % %))))
(transduce xform + [1 2 3 4 5]) ; 1 + 9 + 25 = 35
```
## 매 결정 기준
| 상황 | FP fit |
|---|---|
| Concurrent / parallel | High — immutability eliminates race |
| Compilers / parsers | High — ADT + pattern match natural fit |
| UI state management | High — Redux/Elm pure update |
| Game loop (perf-critical) | Low — manual memory + mutation 필요 |
| OS kernel / driver | Low — direct hardware control 필요 |
| Domain modeling | High — ADT 가 매 invariants 표현 |
**기본값**: 매 mainstream language 에서 매 pure function preference + immutable default + side effect 격리.
## 🔗 Graph
- 응용: [[프론트엔드 및 UIUX 표준|Redux]] · [[CQRS]]
- Adjacent: [[Immutability]] · [[Type Theory]] · [[Algebraic Data Types]]
## 🤖 LLM 활용
**언제**: 매 refactor toward purity, type signature 설계, monad/applicative usage 설명.
**언제 X**: 매 hot loop micro-opt — mutation + cache locality 가 더 빠름.
## ❌ 안티패턴
- **Premature abstraction**: 매 Functor/Monad 도입했는데 매 use case 1개 → 매 cognitive overhead.
- **Pure obsession**: 매 logging/IO 도 monad transformer stack — 매 maintenance 지옥.
- **Recursion without TCO**: 매 stack overflow (Python — TCO 없음).
- **Over-currying**: 매 모든 function 1-arg curried → 매 readability 저하.
## 🧪 검증 / 중복
- Verified (Hutton, "Programming in Haskell", 2nd ed., 2016).
- Verified (Okasaki, "Purely Functional Data Structures", 1998).
- Verified (Wadler, "Theorems for free!", 1989).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — pure FP + modern Haskell/Scala/Rust patterns |