函数式编程
函数式编程核心概念、组合技巧与实际应用
目录
核心概念
进阶主题
学习路径
1. 理解纯函数与副作用
2. 掌握柯里化与函数组合
3. 熟悉高阶函数(map、filter、reduce)
4. 学习函子与Monad
5. 在实际项目中应用核心原则
| 原则 | 说明 |
|---|---|
| 纯函数 | 相同输入始终相同输出,无副作用 |
| 不可变数据 | 不修改原始数据,创建新数据 |
| 函数是一等公民 | 函数可作为参数、返回值、赋值 |
| 声明式编程 | 告诉做什么,而非怎么做 |
| 组合优于继承 | 通过函数组合构建复杂逻辑 |
常用工具函数
javascript
// pipe - 从左到右执行函数
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x)
// compose - 从右到左执行函数
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x)
// curry - 柯里化
const curry = fn => (...args) => {
if (args.length >= fn.length) return fn(...args)
return (...more) => fn(...args, ...more)
}
// memoize - 记忆化
const memoize = fn => {
const cache = new Map()
return (...args) => {
const key = JSON.stringify(args)
if (cache.has(key)) return cache.get(key)
const result = fn(...args)
cache.set(key, result)
return result
}
}