学习笔记——函数组合

纯函数和柯里化很容易写出洋葱代码 h(g(f(x)))

函数组合可以让我们把细粒度的函数重新组合生成一个新的函数


函数组合

  • 函数组合 (compose):如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数
    • 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果
    • 函数组合默认是从右到左执行
      在这里插入图片描述
      在这里插入图片描述
fn = compose(f1, f2, f3)
b = fn(a)
// 组合函数
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)   // 可在 MDN 查看 redece() 方法的的说明
	}
}
// ES6
const compose = (...fns) => value => fns.reverse().reduce((acc, fn) =>
fn(acc), value)

MDN:https://developer.mozilla.org/zh-CN/docs/Web

  • 函数的组合要满足结合律 (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
调试
  • 如何调试组合函数
const f = _.flowRight(_.toUpper, _.first, _.reverse)
console.log(f(['one', 'two', 'three']))
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 的方法
// 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')
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: 我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参
数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数。

  • 不需要指明处理的数据

  • 只需要合成运算过程

  • 需要定义一些辅助的基本运算函数

const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' '))

案例:

// 非 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 的模式,把单词中的首字母提取并转换成大写:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值