什么是函数组合

173 阅读2分钟

这是我参与更文挑战的第6天,活动详情查看:更文挑战

什么是函数组合

  • 纯函数和柯里化很容易写出洋葱代码 h(g(f(x)))
    • 获取数组的最后一个元素再转换成大写字母,_.toUpper(_.first(_.reverse(array))) image.png
  • 函数组合可以让我们把细粒度的函数重新组合生成一个新的函数

管道

函数组合的出现,先了解一下管道。
下面这张图表示程序中使用函数处理数据的过程,给 fn 函数输入参数 a,返回结果 b。可以想想 a 数据通过一个管道得到了 b 数据。 image.png 当 fn 函数比较复杂的时候,我们可以把函数 fn 拆分成多个小函数,此时多了中间运算过程产生的 m 和 n。 下面这张图中可以想象成把 fn 这个管道拆分成了3个管道 f1, f2, f3,数据 a 通过管道 f3 得到结果 m,m再通过管道 f2 得到结果 n,n 通过管道 f1 得到最终结果 b image.png

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

函数组合

  • 函数组合 (compose):如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数
    • 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果
    • 函数组合默认是从右到左执行
// 组合函数
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() 是从右到左运行,使用的更多一些
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 方法
// 多函数组合
function compose (...fns) {
    return function (value) {
    return fns.reverse().reduce(function (acc, fn) {
            return fn(acc)
        }, value)
    }
}
// ES6
const compose = (...fns) => value => fns.reverse().reduce((acc, fn) => fn(acc), value)
  • 函数的组合要满足结合律 (associativity):
    • 我们既可以把 g 和 h 组合,还可以把 f 和 g 组合,结果都是一样的
// 结合律(associativity)
let f = compose(f, g, h)
let associative = compose(compose(f, g), h) == compose(f, compose(g, h))
// true
  • 所以代码还可以像下面这样
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