Functional Programming

In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead of statements. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

函数式编程是一种编程范式-一种构造计算机程序的结构和元素的风格-将程序中的计算像数学函数的运算一样对待,并且避免改变程序的状态和数据。它是一种声明式编程范式,这意味着程序由表达式和声明组成,而不是由语句。在函数式编程代码中,一个函数的输出只与传入函数的参数有关,所以,同一个函数的任意两次参数相同的调用,它们的返回值完全一致。函数式编程消除了函数副作用,即,程序状态的改变不是由函数的输入来决定,这提高了可读性和程序行为的可预测性,而这些是函数式编程发展的关键因素。
 

JS中的函数式编程:函数可以作为另一个函数的参数,并可以返回一个函数作为输出。

一个例子:

function memoize(f) {
    var cache = {};  // Value cache stored in the closure.

    return function() {
        // Create a string version of the arguments to use as a cache key.
        var key = arguments.length + Array.prototype.join.call(arguments,",");
        if (key in cache) return cache[key];
        else return cache[key] = f.apply(this, arguments);
    };
}
function gcd(a,b) {  // Type checking for a and b has been omitted
    var t;                            // Temporary variable for swapping values
    if (a < b) t=b, b=a, a=t;         // Ensure that a >= b
    while(b != 0) t=b, b = a%b, a=t;  // This is Euclid's algorithm for GCD
    return a;
}

var gcdmemo = memoize(gcd);
gcdmemo(85, 187)  // => 17

var factorial = memoize(function(n) {
                            return (n <= 1) ? 1 : n * factorial(n-1);
                        });
factorial(5)      // => 120.  Also caches values for 4, 3, 2 and 1.

 

 

转载于:https://my.oschina.net/u/1025329/blog/801787

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值