JavaScriptcallback和函数式编程
“函数式编程只描述对程序的input执行的操作,而不使用临时variables来存储中间结果。
问题是如何应用函数式编程,而使用使用callback的asynchronous模块。 在某些情况下,你喜欢callback函数访问一个调用asynchronous引用的函数,但是callback的签名已经被定义了。
例:
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});
如果必须的话,只要将variables和范围的context
注入到函数中即可。
因为你抱怨的API
fs.readFile(file, (function cb(a, err,result){ print(a+result); }).bind(null, a);
这叫做咖喱。 这是更多的FP。
我认为问题在于你误解了它们使用中间值的含义(或者它们是虚假的,我没有阅读过这个链接)。 考虑一个函数式语言中的variables是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上,下面的内容也不行
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:
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; 返回函数(金额,值){ //这里我们使用提供给我们的“金额”值 //返回的函数将始终返回相同的值 //input...它的“引用透明” //它使用amount_to_incr的“intermediate”值...但是,因为 //这个值不会改变,没关系 return amount_to_incr + value; } } map [1,2,3] add_value(2); // - > [3,4,5]