# 神奇的lambda表达式——函数式编程必学

2019.08.31 17:30 1245浏览

# lambda演算是什么？

lambda演算是一套研究函数定义、函数应用和递归的形式系统。它基本的组成部分就是三种表达式: 1. 函数定义 2. 标识符引用 3.函数应用。

``````const lambda = x => x + 1;
``````

lambda演算中的一些基本规则，可以类比到我们比较熟悉的ES6语法:

lambda表达式 ES6 箭头函数

# 如何实现

## 数字

``````const ZERO = f => x => x;
const ONE = f => x => f(x);
const TWO = f => x => f(f(x));
...
``````

``````const toNumber = n => n(i => i+1)(0);
console.log(toNumber(ONE));
// 1
``````

## 计算

``````const add = n => m => fn => x => m(fn)(n(fn)(x));

toNumber(THREE);
// 3
``````

``````const multiply = n => m => fn => x => m(n(fn))(x);

const result = toNumber(multiply(TWO)(THREE));
console.log(result);
// 6
``````

## 控制语句

``````const TRUE = first => second => first;
const FALSE = first => second => second;
``````

``````const ifElse = boolFn => first => second => boolFn(first)(second);
// ifElse(TRUE)(x)(y) ===> x
// ifElse(FALSE)(x)(y) ===> y
``````

``````const toBoolean = boolFn => boolFn(true)(false);

console.log(toBoolean(TRUE));
// true
``````

## 逻辑

``````const not = boolFn => first => second => boolFn(second)(first);
toBoolean(not(TRUE));
// false
``````

``````const or = first => second => first(first)(second);
toBoolean(or(TRUE)(FALSE)); // true
toBoolean(or(FALSE)(FALSE)); // false
toBoolean(or(TRUE)(FALSE)) // true
``````

``````const and = first => second => first(second)(first);
toBoolean(and(FALSE)(FALSE)); // false
toBoolean(and(FALSE)(TRUE)); // false
toBoolean(and(TRUE)(TRUE)); // true
``````

## 递归(Y组合子)

``````const factrial => n => n == 0 ? 1 : n * factrial(n - 1);
``````

``````const makeFactorial = factroial => n => n == 0 ? 1 : n * factroial(n - 1);
``````

``````const seed = n => n;
``````

``````const factorial0 = makeFactorial(seed)
``````

``````const factorial0 = n => n == 0 ? 1 : n * (n => n)(n - 1);
``````

``````const factorial1 = makeFactorial(factorial0)
``````

``````const factorial1 = n => n == 0 ? 1 : n * factorial0(n - 1);
``````

``````const factorialn = makeFactorial(makeFactorial(...)); // 无穷个makeFactorial
``````

``````const loop = x => x(x);
``````

``````const loop = (x => x(x))(x => x(x))
``````

``````const loop = (x => x(x))(x => x(x))
``````

``````const loop = (x => x(x))(y => x(x)(y))
``````

``````const factorial = loop(makeFactorial);
``````

``````factorial(4) = 24
``````

2人点赞

• 2
• 评论
• 收藏
• 共同学习，写下你的评论

0/150