d8a80f6272
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해 끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은 과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업. 도구: Datacollect/scripts/link_reconcile_apply.mjs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
219 lines
6.4 KiB
Markdown
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 |
|