dot 函数是 binary,因为它接收两个参数;然而我们可以将它手动转换成两个 unary 函数,就像下面的例子。留意 curriedDot 是一个 unary 函数,它接收一个向量并返回另一个接收第二个向量的 unary 函数。
映射 和 集合 也很类似。可以经由过程返回一个新的修改好的映射或者集合来代替应用会修改其本身的函数。
- function curriedDot(vector1) {
- return function(vector2) {
- return vector1.reduce((sum, element, index) => sum += element * vector2[index], 0);
- }
- }
- // Taking the dot product of any vector with [1, 1, 1]
- // is equivalent to summing up the elements of the other vector.
- const sumElements = curriedDot([1, 1, 1]);
- console.log(sumElements([1, 3, -5])); // -1
- console.log(sumElements([4, -2, -1])); // 1
很荣幸,我们不须要把每一个函数都手动转换成柯里化今后的情势。Ramda 和 lodash 等库可认为我们做这些工作。实际上,它们是柯里化的混淆情势。你既可以每次传递一个参数,也可以像本来一样一次传递所有参数。
- function dot(vector1, vector2) {
- return vector1.reduce((sum, element, index) => sum += element * vector2[index], 0);
- }
- const v1 = [1, 3, -5];
- const v2 = [4, -2, -1];
- // Use Ramda to do the currying for us!
- const curriedDot = R.curry(dot);
- const sumElements = curriedDot([1, 1, 1]);
- console.log(sumElements(v1)); // -1
- console.log(sumElements(v2)); // 1
- // This works! You can still call the curried function with two arguments.
- console.log(curriedDot(v1, v2)); // 3
Ramda 和 lodash 都许可你“跳过”一些变量之后再指定它们。它们应用置位符来做这些工作。因为点积的计算可以交换两项。传入向量的次序不影响结不雅。让我们换一个例子来阐述若何应用一个置位符。Ramda 应用双下划线作为其置位符。
- const giveMe3 = R.curry(function(item1, item2, item3) {
- return `
- 1: ${item1}
- 2: ${item2}
- 3: ${item3}
- `;
- });
- const giveMe2 = giveMe3(R.__, R.__, 'French Hens'); // Specify the third argument.
- const giveMe1 = giveMe2('Partridge in a Pear Tree'
推荐阅读
沙龙晃荡 | 去哪儿、陌陌、ThoughtWorks在主动化运维中的实践!10.28不见不散! 几周前,我们开端写一个系列,>>>详细阅读
地址:http://www.17bianji.com/lsqh/38230.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示