函数组合
- 函数组合可以让我们把细粒度的函数重新组合生成一个新的函数
- 纯函数和柯里化很容易写出洋葱代码 h(g(f(x)))
- 获取数组的最后一个元素再转换成大写字母, _.toUpper(_.first(_.reverse(array)))
管道
下面这张图表示程序中使用函数处理数据的过程,给 fn 函数输入参数 a,返回结果 b。可以想想 a 数据
通过一个管道得到了 b 数据。
当 fn 函数比较复杂的时候,我们可以把函数 fn 拆分成多个小函数,此时多了中间运算过程产生的 m 和n。
下面这张图中可以想象成把 fn 这个管道拆分成了3个管道 f1, f2, f3,数据 a 通过管道 f3 得到结果 m,m再通过管道 f2 得到结果 n,n 通过管道 f1 得到最终结果 b1
2fn = compose(f1, f2, f3)
b = fn(a)
函数组合
函数组合 (compose):如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数
- 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果
- 函数组合默认是从右到左执行
1 | // 组合函数 |
lodash 中的组合函数
- lodash 中组合函数 flow() 或者 flowRight(),他们都可以组合多个函数
- flow() 是从左到右运行
- flowRight() 是从右到左运行,使用的更多一些
1 | const _ = require('lodash') |
模拟实现 lodash 的 flowRight 方法1
2
3
4
5
6
7
8
9
10
11// // 多函数组合
function compose (...args) {
return function (value) {
return args.reverse().reduce(function (val, cur) {
return cur(val)
}, value)
}
}
// ES6
const compose = (...fns) => value => fns.reverse().reduce((val, cur) => cur(val), value)
函数的组合要满足结合律 (associativity):
- 我们既可以把 g 和 h 组合,还可以把 f 和 g 组合,结果都是一样的
1
2
3
4// 结合律(associativity)
let f = compose(f, g, h)
let associative = compose(compose(f, g), h) == compose(f, compose(g, h))
// true
所以代码还可以像下面这样1
2
3
4
5
6const _ = require('lodash')
// const f = _.flowRight(_.toUpper, _.first, _.reverse)
// const f = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse)
const f = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))
console.log(f(['one', 'two', 'three']))
// => THREE
调试
如何调试组合函数1
2const f = _.flowRight(_.toUpper, _.first, _.reverse)
console.log(f(['one', 'two', 'three']))
1 | const _ = require('lodash') |
lodash/fp
- lodash 的 fp 模块提供了实用的对函数式编程友好的方法
- 提供了不可变 auto-curried iteratee-first data-last 的方法
1 | // lodash 模块 |
1 | const fp = require('lodash/fp') |
Point Free
Point Free:我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数。
- 不需要指明处理的数据
- 只需要合成运算过程
- 需要定义一些辅助的基本运算函数
1 | const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' ')) |
1 | // 非 Point Free 模式 |
使用 Point Free 的模式,把单词中的首字母提取并转换成大写1
2
3
4
5const fp = require('lodash/fp')
const firstLetterToUpper = fp.flowRight(join('. '),
fp.map(fp.flowRight(fp.first, fp.toUpper)), split(' '))
console.log(firstLetterToUpper('world wild web'))
// => W. W. W