首页天道酬勤编写函数求组合数,函数式编程入门

编写函数求组合数,函数式编程入门

admin 08-14 05:13 147次浏览

概念 纯函数和柯里化很容易写出洋葱代码_.toUpper(_.first(_.reverse(array))); //这样就是洋葱代码 一层套一层函数组合可以把细粒度的函数重新组合成一个新函数函数组合(compose):如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数函数就像是数据的管道,函数组合就是把这些管道连接起来,网数据穿过多个管道形成最终的结果 函数组合默认是从右往左执行function compose(f, g) { return function(value) { return f(g(value)) }};let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];function reverse(array) {//数组的逆转 return array.reverse(array)};function first(array) {//拿到数组的第一位 return array[0] }//先执行reverse函数 后执行first函数const last = compose(first, reverse)console.log(last(arr)); //9 lodash中的组合函数 1、flow()函数 从左往右执行2、flowRight()函数 从右往左执行 这个函数用的多一些这两个都可以组合多个函数举例://定义数组let array = ['first', 'second', 'third', 'four', 'five'];//数组逆转const reverse = arr => arr.reverse();//数组的第一个const first = arr => arr[0]//转换大写const toUpPer = element => element.toUpperCase()//封装方法const last = _.flowRight(toUpPer, first, reverse)//得到结果console.log(last(array)); //FIVE 组合函数实现原理

模拟lodash中的flowRight

组合函数原理模拟function compose(...args) { return function(value) { return args.reverse().reduce(function(acc, fn) { return fn(acc) }, value) }}const last1 = compose(toUpPer, first, reverse)console.log(last1(array)); //FIVE//使用箭头函数重写const compose = (...args) => (value) => args.reverse().reduce((acc, fn) => fn(acc), value)const last1 = compose(toUpPer, first, reverse)console.log(last1(array)); //FIVE 函数组合要满足的条件 函数的组合要满足结合律(associativity)我们既可以把g和h组合 ,还可以吧把f和g组合,结果都是一样的let f = compose(f, g, h)let associative = compose(compose(f,g,h)) == compose(f,compose(g,h))举例 使用lodash自带的函数组合const last = _.flowRight(_.toUpper, _.first, _.reverse); console.log(last(array));//FIVEconst last = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse); console.log(last(array));//FIVEconst last = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse)); console.log(last(array));//FIVE

谢谢大家观看 如有不足敬请指教

iOS中的UIKeyboard键盘视图使用方法小结Django项目如何创建
如何理解函数式编程,数学组合函数 最浪漫的函数曲线,最浪漫的数学题函数
相关内容