“功能编程仅描述了对程序输入执行的操作,而不使用临时变量来存储中间结果。”
问题是如何应用函数式编程,并使用使用回调的异步模块。
在某些情况下,您喜欢使用回调来访问调用异步引用所构成的函数的变量,但已经定义了回调的签名。
例:
function printSum(file,a){
//var fs =....
var c = a+b;
fs.readFile(file,function cb(err,result){
print(a+result);///but wait, I can't access a......
});
}
当然我可以访问一个,但它将违背纯函数式编程范式
fs.readFile(file, (function cb(err,result){
print(this.a+result);
}).bind({a: a});
刚注射 context
如果必须,将变量和范围放入函数中。
因为你抱怨API
fs.readFile(file, (function cb(a, err,result){
print(a+result);
}).bind(null, a);
这叫做currying。这是更多的FP。
我认为问题在于你误解了他们使用中间值的含义(或者他们歪曲了它,我没有读过这个链接)。考虑到函数式语言中的变量是 definition
某事,那个定义不能改变。在函数式编程中使用值/公式的名称是完全可以接受的,只要它们不会改变。
function calculate(a,b,c) {
// here we define an name to (a+b) so that we can use it later
// there's nothing wrong with this "functionally", since we don't
// change it's definition later
d = a + b;
return c * d;
}
另一方面,以下功能不正常
function sum(listofvalues) {
sum = 0;
foreach value in listofvalues
// this is bad, since we're re-defining "sum"
sum += value;
return sum
}
对于更接近代码中的内容...考虑一下函数调用 map that takes a list of things and a function to apply to a thing and returns a new list of things. It's perfectly acceptable to say:
function add_value(amount){
amount_to_incr =金额* 2;
返回函数(金额,值){
//这里我们使用提供给我们的“金额”值
//返回的函数将始终返回相同的值
//输入......它的“引用透明”
//它使用了amount_to_incr的“中间”值...但是,因为
//该值不会改变,没关系
return amount_to_incr + value;
}
}
map [1,2,3] add_value(2); // - > [3,4,5]