// 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);
function addBy(value)
{
return function(n) {
// 将value 的进行闭包处理
return n + value;
};
}
var add10 = addBy(10);
var result11 = add10(1);
// orElse
var result11 = addBy(10)(1);
多个参数时: let fakeAddFn n1 = fun n2 -> fun n3 -> fun n4 -> n1 + n2 + n3 + n4
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
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