函数组合
纯函数和柯里化很容易写出洋葱代码h(g(f(x)))
- 获取数组的最后一个元素再转换成大写字母, .toUpper(.first(_.reverse(array)))
函数组合可以让我们把细粒度的函数重新组合成一个新的函数
管道
下面这张图表示程序中使用函数处理数据的过程,给 fn 函数输入参数 a,返回结果 b。可以想想 a 数据通过一个管道得到了 b 数据。
将函数理解为管道,当函数复杂时,可以把函数fn拆分成多个小函数,此时多了中间运算过程产生的m和n
下面这张图中可以想象成把 fn 这个管道拆分成了3个管道 f1, f2, f3,数据 a 通过管道 f3 得到结果 m,m再通过管道 f2 得到结果 n,n 通过管道 f1 得到最终结果 b
fn = compose(f1, f2, f3)
b = fn(a)
函数组合
如果一个函数要经过多个函数处理才能得到最终值,可以把中间过程的函数合并成一个函数
函数就像数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果,函数组合默认从右到左执行
function compose(f, g){
return function(value){
return f(g(value))
}
}
function reverse(array){
return array.reverse()
}
function first(array){
return array[0]
}
const last = compose(first, reverse)
lats([1,2,3,4])
lodash中的函数组合
flow或者flowRight,从左到右和从右到左.
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s = s.toUpperCase()
const f = _.flowRight(toUpper, first, reverse)
f(['one','two','three'])
原理模拟
function compose(...args){
return function(value){
return args.reverse().reduce(function(acc, currentValue){
return currentValue(acc)
},value)
}
}
const compose = (...args) => value => args.reverse().reduce(
(acc,fn) => fn(acc), value)
函数的组合要满足结合律
我们既可以把 g 和 h 组合,还可以把 f 和 g 组合,结果都是一样的
const f1 = _.flowRight(_.toUpper, _.first, _.reverse)
const f2 = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse)
const f3 = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))
调试
//写组合函数时,curry方法的参数第一个是已确定的,第二个是等待传递进来的
const split = _.curry((sep, str) => _.split(str, sep))
const join = _.curry((sep, str) => _.join(array, sep))
const map = _.curry((array, fn) => _.map(array, fn))
const trace = _.curry((tag, v) => {
console.log(tag, v)
return v
})
//将trace函数插在组合函数中间,查看值的变化
const f = _.flowRight(join('-'), map(_.toLower), trace('split之后'),split(' '))
console.log(f('NEVER GIVE UP))
lodash的fp模块
- 提供了实用的对函数式编程友好的方法
- 提供已被柯里化,不可变的函数优先,数据其后的方法 ```javascript const fp = require(‘lodash/fp’)
.map([‘a’, ‘b’, ‘c’], .toUpper)//数据优先,函数其后 fp.map(fp.toUpper, [‘a’, ‘b’, ‘c’])//函数优先,数据之后 fp.map(fp.toUpper)([‘a’, ‘b’, ‘c’])
const f = fp.flowRight(fp.join(‘-‘), fp.map(fp.toLower), fp.split(‘ ‘))
<a name="i5QOo"></a>
## map方法的问题
```javascript
_.map(['23', '8', '10'], parseInt)//[23, NaN, 2]
fp.map(parseInt, ['23', '8', '10'])
//所接收的函数参数不同