Din*_*Liu 14 javascript functional-programming currying composition
最近我在一本Javascript书中读到了函数组合,然后在一个网站上我看到有人将它称为currying.
它们是相同的概念吗?
Tha*_*you 16
@ Omarjmh的回答很好,但是对于学习者而言,这个组合的例子非常复杂,在我看来
它们是相同的概念吗?
没有.
首先,currying将一个将多个参数转换为函数序列的函数进行转换,每个函数都接受一个参数.
// not curried
const add = (x,y) => x + y;
add(2,3); // => 5
// curried
const add = x => y => x + y;
add(2)(3); // => 5
Run Code Online (Sandbox Code Playgroud)
请注意应用curried函数的独特方式,一次一个参数.
其次,函数组合是将两个函数组合成一个,当应用时,返回链接函数的结果.
const compose = f => g => x => f(g(x));
compose (x => x * 4) (x => x + 3) (2);
// (2 + 3) * 4
// => 20
Run Code Online (Sandbox Code Playgroud)
这两个概念密切相关,因为它们相互配合良好.通用函数组合使用一元函数(带有一个参数的函数)和curried函数也只接受一个参数(每个应用程序).
// curried add function
const add = x => y => y + x;
// curried multiplication function
const mult = x => y => y * x;
// create a composition
// notice we only apply 2 of comp's 3 parameters
// notice we only apply 1 of mult's 2 parameters
// notice we only apply 1 of add's 2 parameters
let add10ThenMultiplyBy3 = compose (mult(3)) (add(10));
// apply the composition to 4
add10ThenMultiplyBy3(4); //=> 42
// apply the composition to 5
add10ThenMultiplyBy3(5); //=> 45
Run Code Online (Sandbox Code Playgroud)