函数组合、函子

函数组合

image.png
函数组合 (compose):只关心3个小函数,和输入,不关心中间结果

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

// 组合函数
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = str => str.toUpperCase()

const f = compose(toUpper, first, reverse)
function compose(...args) {
    return function(value) {
        return args.reverse().reduce(function(total, func) {
            return func(total)
        },value)
    }
}

console.log(f(['askj', 'rose', 'jack']))

// Pointfree
// world hello you => W. H. Y.
const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.flowRight(fp.toUpper, fp.first)) ,fp.split(' '))
console.log(firstLetterToUpper('world hello you'))
复制代码

目的:最大限度的,保证函数的复用

函子

通过函子可以控制副作用,处理函数异常,异步操作等

  • 函数式编程的运算不直接操作值,而是由函子完成
  • 函子就是一个实现了 map 契约的对象
  • 我们可以把函子想象成一个盒子,这个盒子里封装了一个值
  • 想要处理盒子中的值,我们需要给盒子的 map 方法传递一个处理值的函数(纯函数),由这个函数来对值进行处理
  • 最终 map 方法返回一个包含新值的盒子(函子)
// 函子
 class Container {
    static of (value) {
       return new Container(value)
    }

     constructor (value) {
        this._value = value
     }

     map (fn) {
        return Container.of(fn(this._value))
     }
 }

 let r = Container.of(5)
            .map(x => x + 2)
            .map(x => x * x)

 console.log(r)
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享