js函數式編程

最近在看樸靈的《深刻淺出nodejs》其中講到函數式編程.理解記錄下java

  • 高階函數

比較常見,即將函數做爲參數,或是將函數做爲返回值得函數.node

如ECMAScript5中提供的一些數組方法 forEach() map() reduce() reduceRight() filter() every() some() 編程

  • 偏函數

說實話看到書,我是第一次看到這個概念,雖然應該是看到過這種用法,好桑感....定義也比較拗口數組

指建立一個調用另一個部分---參數或變量已經預知的函數---的函數的用法.直白說就是:經過閉包來建立預先填寫好的某些參數的函數."能夠經過這個來建立動態名稱的函數,看起來應該很牛B,代碼可讀性也更好"閉包

寫個例子app

         var joinwords  = function(first,sec){
             return [first, sec].join(' ');
         }    
    
        function suffix(a){
          return function(b){
             return joinwords(b,a);
          }
        }
    
        var hello = suffix("world");
 /*
   function hello (b){
     return [b,"world"].join();
   }
 * */

    console.log(hello("hello")); // hello world

 

 ----------------------------------------2014-02-11更新-----------------------------------------------------------------------函數式編程

看了篇文章,函數柯里化與偏應用,講的挺好的,爲加深印象,本身再整理理解下函數

柯里化(Currying)spa

柯里化是將一個多元函數分解爲一系列嵌套調用的一元函數。分解後,你能夠部分應用一個或多個參數。柯里化的過程不會向函數傳遞參數。code

偏應用(Partial Application)

偏應用是爲一個多元函數預先提供部分參數,從而在調用時能夠省略這些參數。

 如今將上面的示例柯里化

function rightmostCurry (binaryFn) {
  return function (secondArg) {
    return function (firstArg) {
      return binaryFn(firstArg, secondArg);
    };
  };
};

//調用
var rightmostCurriedMap = rightmostCurry(joinwords),
    squareAll = rightmostCurriedMap("world");
console.log(rightmostCurry(joinwords)("Chan")("Nancy")); // Nancy Chan
console.log(rightmostCurriedMap("July")("Hey")); // Hey July
console.log(squareAll("hello")); // hello world
console.log(squareAll("hello2")); // hello2 world  

When  to use Currying (這篇文章講到了,看得有點懵...)

When you find yourself calling the same function and passing mostly the same parameters, then the function is probably a good candidate for currying. You can create a new function dynamically by partially applying a set of arguments to your function. The new function will keep the repeated parameters stored (so you don't have to pass them every time) and will use them to pre-fill the full list of arguments that the original function expects.

相關文章
相關標籤/搜索