zoukankan      html  css  js  c++  java
  • js函数式编程

    最近在看朴灵的《深入浅出nodejs》其中讲到函数式编程.理解记录下

    • 高阶函数

    比较常见,即将函数作为参数,或是将函数作为返回值得函数.

    如ECMAScript5中提供的一些数组方法 forEach() map() reduce() reduceRight() filter() every() some() 

    • 偏函数

    说实话看到书,我是第一次看到这个概念,虽然应该是看到过这种用法,好桑感....定义也比较拗口

    指创建一个调用另外一个部分---参数或变量已经预知的函数---的函数的用法.直白说就是:通过闭包来创建预先填写好的某些参数的函数."可以通过这个来创建动态名称的函数,看起来应该很牛B,代码可读性也更好"

    写个例子

             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)

    柯里化是将一个多元函数分解为一系列嵌套调用的一元函数。分解后,你可以部分应用一个或多个参数。柯里化的过程不会向函数传递参数。

    偏应用(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.

  • 相关阅读:
    1017.陶陶装苹果
    1084.爬楼梯加强版
    1056.A ^ B Problem 快速幂算法。
    1074.我们喜欢递归的斐波那契数列
    1073.我们喜欢递归的阶乘
    1046 没过
    python 基本常用数据类型
    yii2.0 数据库查询操作
    python 随便笔记
    搭建自己的koa+mysql后台模板
  • 原文地址:https://www.cnblogs.com/kite-Runner/p/3543692.html
Copyright © 2011-2022 走看看