# 学会使用函数式编程的程序员(第1部分)

https://promotion.aliyun.com/...

## 纯函数(Purity)

``````var z = 10;
return x + y;
}
``````

``````function justTen() {
return 10;
}
``````

``````function addNoReturn(x, y) {
var z = x + y
}
``````

``````writeFile(fileName);
updateDatabaseTable(sqlCmd);
sendAjaxRequest(ajaxRequest);

``````

## 不可变性 (Immutability)

``````var x = 1;
x = x + 1;

``````

``````addOneToSum y z =
let
x = 1
in
x + y + z
``````

`let`块中，`x`被绑定到`1`的值上，也就是说，它在函数的生命周期内都等于1。当函数退出时，它的生命周期结束，或者更准确地说，当`let`块被求值时，它的生命周期就结束了。

`in`块中，计算可以包含在`let`块中定义的值，即 x，返回计算结果 x + y + z，或者更准确地说，返回 1 + y + z，因为 x = 1。

``````sumRange start end acc =
if start > end then
acc
else
sumRange (start + 1) end (acc + start)
``````

## 高阶函数

``````function validateValueWithFunc(value, parseFunc, type) {
if (parseFunc(value))
console.log('Invalid ' + type);
else
console.log('Valid ' + type);
}
``````

``````validateValueWithFunc('123-45-6789', /^\d{3}-\d{2}-\d{4}\$/.exec, 'SSN');
validateValueWithFunc('(123)456-7890', /^\(\d{3}\)\d{3}-\d{4}\$/.exec, 'Phone');
validateValueWithFunc('Joe Mama', parseName, 'Name');
``````

``````var parseSsn = /^\d{3}-\d{2}-\d{4}\$/.exec;
var parsePhone = /^\(\d{3}\)\d{3}-\d{4}\$/.exec;
validateValueWithFunc('123-45-6789', parseSsn, 'SSN');
validateValueWithFunc('(123)456-7890', parsePhone, 'Phone');
validateValueWithFunc('Joe Mama', parseName, 'Name');
``````

``````function makeRegexParser(regex) {
return regex.exec;
}
var parseSsn = makeRegexParser(/^\d{3}-\d{2}-\d{4}\$/);
var parsePhone = makeRegexParser(/^\(\d{3}\)\d{3}-\d{4}\$/);
validateValueWithFunc('123-45-6789', parseSsn, 'SSN');
validateValueWithFunc('(123)456-7890', parsePhone, 'Phone');
validateValueWithFunc('Joe Mama', parseName, 'Name');
``````

parseSsnparsePhone 实际上与以前一样，是正则表达式的 exec 函数。

``````function makeAdder(constantValue) {
return constantValue + value;
};
}
``````

``````var add10 = makeAdder(10);

``````

## 闭包

``````function grandParent(g1, g2) {
var g3 = 3;
return function parent(p1, p2) {
var p3 = 33;
return function child(c1, c2) {
var c3 = 333;
return g1 + g2 + g3 + p1 + p2 + p3 + c1 + c2 + c3;
};
};
}

``````

``````var parentFunc = grandParent(1, 2); // returns parent()
var childFunc = parentFunc(11, 22); // returns child()
console.log(childFunc(111, 222)); // prints 738
// 1 + 2 + 3 + 11 + 22 + 33 + 111 + 222 + 333 == 738
``````

## 交流

https://github.com/qq44924588...

40750 人关注
454 篇文章