14

「関数型プログラミングは、中間結果を格納するための一時変数を使用せずに、プログラムへの入力に対して実行される操作のみを記述します。」

問題は、関数型プログラミングを適用しながら、コールバックを利用する非同期モジュールを使用する方法です。場合によっては、コールバックが非同期参照を呼び出す関数が提示する変数にアクセスする必要がありますが、コールバックのシグネチャはすでに定義されています。

例:

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

もちろん、私はにアクセスできますが、それは純粋な関数型プログラミングのパラダイムに反します

4

3 に答える 3

10
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);

いわゆるカレーです。これはより多くの FP です。

于 2011-06-14T22:44:05.627 に答える
1

問題は、中間値の使用によって彼らが何を意味するのかを誤解していることだと思います(または、彼らはそれを誤解しています。私はリンクを読んでいません)。関数型言語の変数は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 = amount * 2;
    return function(amount, value) {
        // here we're using that "amount" value provided to us
        // the function returned will always return the same value for the same
        // input... its "referentially transparent"
        // and it uses the "intermediate" value of amount_to_incr... however, since 
        // that value doesn't change, it's fine
        return amount_to_incr + value;
    }
}
map [1,2,3] add_value(2) ;// -> [3,4,5]
于 2011-06-15T04:03:19.387 に答える