什么是柯里化
What is currying
一句话:把「一次收 n 个参数」的函数 改成「每次收一个、返回一个新函数」, 收满了才真正计算。
add(1, 2, 3) 变成add(1)(2)(3)。 实现靠闭包记住已经收到的参数。
有什么用(别只说「炫技」):
- 参数复用——
const log = level => msg => console.log(`[${level}] ${msg}`),然后const warn = log("WARN")。 - 延迟执行—— 参数没收齐就不干活, 适合配置式 API。
- 函数组合—— 组合要求每个函数只收一个参数, 柯里化正好把多参函数改造成这个形状。
会追问:「柯里化和偏函数(partial application)什么区别?」—— 柯里化严格一次一个; 偏函数是一次固定几个、剩下的以后给(bind 就是偏函数)。 这个区分问得不少。
还会让你手写一个通用 curry—— 思路是:参数够了就调,不够就返回一个继续收的函数。
In one line: take a function that receives n arguments at once and reshape it into one that takes one at a time and returns a new function, only computing once they are all in.
add(1, 2, 3) becomes add(1)(2)(3). The implementation rests on a closure remembering the arguments received so far.
What it is good for — do not just say “showing off”:
- Reusing arguments —
const log = level => msg => console.log(`[${level}] ${msg}`), thenconst warn = log("WARN"). - Deferred execution — nothing runs until every argument has arrived, which suits configuration-style APIs.
- Function composition — composition wants every function to take a single argument, and currying reshapes multi-argument functions into exactly that.
Follow-up: “What is the difference between currying and partial application?” — currying is strictly one argument at a time; partial application fixes a few now and takes the rest later (bind is partial application). This distinction comes up a lot.
They will also ask you to write a generic curry — the idea is: if you have enough arguments, call the function; if not, return one that keeps collecting.