首页投稿(暂停使用,暂停投稿)程序员编程语言爱好者

函数式编程的理念

2016-07-01  本文已影响473人  沪上最强亚巴顿

1. FP 理念

1.1 不变性

1.2 声明性风格

// csharp
return sourceList.Where(item => item %2 == 0);
// or LINQ 
stylereturn from item in sourceList where item % 2 == 0 select item;
// if we have a function(abstract) already. 
return sourceList.Where(NumberIsEven);

1.3 类型

1.4 表达式求值

2. 高阶函数

3. 柯里化(Currying) 和部分函数应用

function addBy(value) 
{ 
  return function(n) {  
    // 将value 的进行闭包处理
    return n + value; 
  };
}
var add10 = addBy(10);
var result11 = add10(1);

// orElse
var result11 = addBy(10)(1);

4. 递归及优化

public int Factorial(int n) {
    return n <= ? 1 : n * Factorial(n - 1);
}
>> 每次递归都卡在了n*_ 上, 必须等后面的结果返回后,当前函数的调用栈才能返回.
n               (n-1)       ...      3         2       1  // state
--------------------------------------------------------
n*f(n-1) -> (n-1)*f(n-2) -> ... -> 3*f(2) -> 2*f(1) -> 1  // stack in
                                                       |  
n*r      <-  (n-1)*(r-1) <- ... <-   3*2  <-   2*1  <- 1  // stack out

private int FactorialHelper(acc, n) {
    return n <= 1 ? acc : FactorialHelper(acc * n, n - 1);
}
public int Factorial(int n) { return FactorialHelper(1, n); }

init        f(1, n)             // stack in
                |               // stack pop, jump to next
n           f(n, n-1)           // stack in
                |               // stack pop, jump to next
n-1         f(n*(n-1), n-2)     // stack in
                |               // stack pop, jump to next
...         ...                 // stack in
                |               // stack pop, jump to next
2           f((k-1), 1)         // stack in
                |               // stack pop, jump to next
1           k                   // return result

5. 记忆化

let memorize f =
    let cache = new Dictionary<_, _>()
    fun p ->
        match cache.TryGetValue(p) with
        | true, result -> result
        | _ ->
            let result = f p
            cache.Add(p, result)
            result

6. 惰性求值

7. 延迟

// binding:
('a -> 'b)    -> 'a -> 'b
// map:
('a -> 'b)    -> M<'a> -> M<'b>
// bind:
('a -> M<'b>) -> M<'a> -> M<'b>

10. Mics

上一篇 下一篇

猜你喜欢

热点阅读