问题 JavaScript回调和函数式编程


“功能编程仅描述了对程序输入执行的操作,而不使用临时变量来存储中间结果。”

问题是如何应用函数式编程,并使用使用回调的异步模块。 在某些情况下,您喜欢使用回调来访问调用异步引用所构成的函数的变量,但已经定义了回调的签名。

例:

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......
     });
}

当然我可以访问一个,但它将违背纯函数式编程范式


9759
2018-06-14 22:31


起源

你可以访问 a 在你的功能。它在一个 关闭 - hvgotcodes
我想你可以访问 a - Karoly Horvath
函数式编程的定义是可疑的;你从哪里得到那个的? FP的中间结果没有错。 - Jacob
定义: ibm.com/developerworks/library/wa-javascript/... - DuduAlul
我试图了解FP人如何克服这些“问题”.. - DuduAlul


答案:


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。


10
2018-06-14 22:44



那太恶心了 - DuduAlul
我的意思是,它有效,但它看起来不太好.. - DuduAlul
@MrOhad这是将状态注入回调的唯一方法。向上移动范围链或将数据注入上下文。实际上还有另一种选择。我添加了可能更好的currying示例。 - Raynos


我认为问题在于你误解了他们使用中间值的含义(或者他们歪曲了它,我没有读过这个链接)。考虑到函数式语言中的变量是 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]

0
2018-06-15 04:03



考虑到多个负面的支持者,我很感激有关他们应该得到什么的评论。知道我哪里错了,以及我能纠正什么,真好。 - RHSeeger