函数组合

函数组合

  • 函数组合可以让我们把细粒度的函数重新组合生成一个新的函数
  • 纯函数和柯里化很容易写出洋葱代码 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 得到最终结果 b
管道

1
2
fn = compose(f1, f2, f3)
b = fn(a)

函数组合

函数组合 (compose):如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数

  • 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果
  • 函数组合默认是从右到左执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 组合函数
function compose (f, g) {
return function (x) {
return f(g(x))
}
}
function first (arr) {
return arr[0]
}
function reverse (arr) {
return arr.reverse()
}
// 从右到左运行
let last = compose(first, reverse)
console.log(last([1, 2, 3, 4]))

lodash 中的组合函数

  • lodash 中组合函数 flow() 或者 flowRight(),他们都可以组合多个函数
  • flow() 是从左到右运行
  • flowRight() 是从右到左运行,使用的更多一些
1
2
3
4
5
6
const _ = require('lodash')
const toUpper = s => s.toUpperCase()
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))

模拟实现 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
6
const _ = 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
2
const f = _.flowRight(_.toUpper, _.first, _.reverse)
console.log(f(['one', 'two', 'three']))

1
2
3
4
5
6
7
8
9
10
const _ = require('lodash')
const trace = _.curry((tag, v) => {
console.log(tag, v)
return v
})
const split = _.curry((sep, str) => _.split(str, sep))
const join = _.curry((sep, array) => _.join(array, sep))
const map = _.curry((fn, array) => _.map(array, fn))
const f = _.flowRight(join('-'), trace('map 之后'), map(_.toLower), trace('split 之后'), split(' '))
console.log(f('NEVER SAY DIE'))

lodash/fp

  • lodash 的 fp 模块提供了实用的对函数式编程友好的方法
  • 提供了不可变 auto-curried iteratee-first data-last 的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// lodash 模块
const _ = require('lodash')
_.map(['a', 'b', 'c'], _.toUpper)
// => ['A', 'B', 'C']
_.map(['a', 'b', 'c'])
// => ['a', 'b', 'c']
_.split('Hello World', ' ')

// lodash/fp 模块
const fp = require('lodash/fp')
fp.map(fp.toUpper, ['a', 'b', 'c'])
fp.map(fp.toUpper)(['a', 'b', 'c'])
fp.split(' ', 'Hello World')
fp.split(' ')('Hello World')
1
2
3
const fp = require('lodash/fp')
const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' '))
console.log(f('NEVER SAY DIE'))

Point Free

Point Free:我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数。

  • 不需要指明处理的数据
  • 只需要合成运算过程
  • 需要定义一些辅助的基本运算函数
1
const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' '))
1
2
3
4
5
6
7
8
9
// 非 Point Free 模式
// Hello World => hello_world
function f (word) {
return word.toLowerCase().replace(/\s+/g, '_');
}
// Point Free
const fp = require('lodash/fp')
const f = fp.flowRight(fp.replace(/\s+/g, '_'), fp.toLower)
console.log(f('Hello World'))

使用 Point Free 的模式,把单词中的首字母提取并转换成大写

1
2
3
4
5
const 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

坚持原创技术分享,您的支持将鼓励我继续创作!