2016-10-11 13 views
0

私は約関数をcurryingのJavascriptで読んでいます。私はコンセプトを得て、例は分かりやすいものでした。この機能は実際に何をしていますか?

しかし、その後、記事の著者は、あまりにも多くの機能をカリー化すると、複数のネストされたリターンのためとして乱雑ことができることを述べている、とカレー引数として渡さ別の関数に関数を示します。

var curryIt = function(uncurried) { 

var parameters = Array.prototype.slice.call(arguments, 1); 

return function() { 
    return uncurried.apply(this, parameters.concat(
    Array.prototype.slice.call(arguments, 0) 
    )); 
    }; 
}; 

はその後、このよう

var greeter = function(greeting, separator, emphasis, name) { 
    console.log(greeting + separator + name + emphasis); 
}; 

var greetHello = curryIt(greeter, "Hello", ", ", "."); 

greetHello("Heidi"); //"Hello, Heidi." 
greetHello("Eddie"); //"Hello, Eddie." 

それを適用しcurryItカレー別の関数、その関数です。どのように正確にそれをやっている?

私には馴染みのないコードはありませんが、私はそれを取得しないようです。

+3

ように、多くの場合、それは* [カリー化を行いません](https://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application)*。それは部分的に適用されます。 – Bergi

+0

あなたが単一のものに精通している場合は、正確に何を得ていないのですか? – Bergi

+0

これはカリングを説明するひどい方法のようです。 – Redu

答えて

1

は技術的には、これは部分のアプリケーションであるが、2つのアイデアはとにかくvery closely related.

あり、あなたのコードを打破してみましょう:

var curryIt = function(uncurried) { 
    // Get all of the parameters except for `uncurried` 
    var parameters = Array.prototype.slice.call(arguments, 1); 

    // Return a new function such that... 
    return function() { 
    // The function you passed in, `uncurried` is called 
    return uncurried 

     // apply - Use an array for arguments instead of positional arguments 
     // i.e, f(a, b, c) === f.apply(this, [a, b, c]) 
     .apply(

     // Set the value of `this` in `uncurried` 
     this, 

     // Create a copy of the original `parameters` array and add... 
     parameters.concat(

      // ...the arguments that were passed to the anonymous function 
      Array.prototype.slice.call(arguments, 0) 
    )); 
    }; 
}; 

方法parameters変化を見ることによって、あなたはのための感覚を得ることができます使い方。

var curryIt = function(uncurried) { 
 
    var parameters = Array.prototype.slice.call(arguments, 1); 
 
    console.log('curryIt: ' + parameters.join(' ')); 
 

 
    return function() { 
 
    var newParams = Array.prototype.slice.call(arguments, 0); 
 
    console.log('anonymous: ' + newParams.join(' ')); 
 
    
 
    // Prepare the arguments here so we can see them 
 
    var args = parameters.concat(newParams); 
 
    console.log('Full call: ' + args.join(' ')); 
 
    return uncurried.apply(this, args); 
 
    }; 
 
}; 
 

 
function f(a, b, c, d) { 
 
    console.log('Finished: ' + [a, b, c, d].join(' ')); 
 
    console.log(' '); 
 
} 
 

 
var g = curryIt(f, 1, 2); 
 
g(3, 4); 
 

 
g(10, 20);

関連する問題