Start learning FP

Functional Programming

经过这几天的了解,越觉得 FP 十分有趣
给个例子:

1
2
3
4
5
6
7
8
// a simple function
function add(a, b) {
return a + b
}
/// the same as
let add = function (a, b) {
return a + b
}

在 ES6 中,存在着箭头函数。所以上面的函数可以写成这个形式:

1
let add = (a, b) => a + b

构造另一个 function

现在写一个新的 function :

1
let multiply = (x, y) => x * y

Let’s start

现在我们用上面两个例子计算下 2 * 3 + 2 * 4

1
2
let result = add(multiply(2, 3), multiply(2, 4))
result // 14

试试 2 + (2 + 3) == (2 + 2) + 3是正确的吗:

1
2
3
4
5
let result1 = add(2, add(2, 3))
let result2 = add(add(2, 2), 3)
result1 === result2 // true

// 可以看出 add(a, add(b, c)) === add(add(a, b), c)

再试试 2 * 3 + 2 * 4 === (2 + 4) * 2

1
2
3
4
let result1 = add(multipy(2, 3), multipy(2, 4))
let result2 = multipy(add(3, 4), 2)
result1 === result2 // true
// Nice Job

add 的链式调用

1
2
3
4
5
6
7
8
9
10
function add(n) {
if (n === undefined) {
return add.result
} else {
add.result += n
return add
}
}
add.result = 0
console.log(add(1)(1)(1)())

result:

1
3