函数式编程之函数组合和 Functor(函子)

函数式编程之函数组合和 Functor(函子)

函数组合

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

    • 获取数组的最后一个元素再转换成大写字母,_.toUpper(_.first(_.reverse(array)))

image

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

管道

下面这张图表示程序中使用函数处理数据的过程,给 fn 函数输入参数 a,返回结果 b。可以想象 a 数据通过一个管道得到了 b 数据。

image

当 fn 函数比较复杂的时候,我们可以把函数 fn 拆分成多个小函数,此时多了中间运算过程产生的 m 和 n。

下面这张图中可以想象成把 fn 这个管道拆分成了 3 个管道 f1, f2, f3,数据 a 通过管道 f3 得到结果 m,m 再通过管道 f2 得到 n, n 通过管道 f1 得到最终结果 b。

image

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]reverse

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)

const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
  • 函数的组合要满足结合律(associativity)
    • 我们既可以把 g 和 h 组合,还可以把 f 和 f 组合,结果都是一样的
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']))
// NEVER SAY DIE  --> never-say-die

const _ = require('lodash')

const log = v => {
  console.log(v)
  return v
}

const trace = _.curry((tag, v) => {
  console.log(tag, v)
  return v
})

// _.split()
const split = _.curry((sep, str) => _.split(str, sep))
// _.toLower()
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 的方法
// loadsh 模块
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.splict(' ', 'Hello World')
fp.splict(' ')('Hello World')

const fp = require('lodash/fp')


const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' '))
console.log(f('NEVER SAY DIE'))
// NEVER SAY DIE  --> never-say-die

Point Free

Pointfree 编程风格指南

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'))
  • 使用 Poin Free 模式,把单词中的首字母提取并转换成大写
// 把一个字符串中的首字母提取并转换成大写, 使用. 作为分隔符
// world wild web ==> W. W. W
const fp = require('lodash/fp')

// const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.first), fp.map(fp.toUpper), fp.split(' '))
const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.flowRight(fp.first, fp.toUpper)), fp.split(' '))

console.log(firstLetterToUpper('world wild web'))

Functor(函子)

为什么要学习函子

学习函子是为了将在函数式编程中把副作用控制在可控的范围内、异常操作、异步操作等。

什么 Functor

  • 容器:包含值和值的变形关系(这个变形关系就是函数)
  • 函子:是一个特殊的容器,通过一个普通的对象来实现,该对象具有 map 方法,map 方法可以运行一个函数对值进行处理(变形关系)

Functor 函子

// 一个容器,包裹一个值
class Container {
  // of 静态方法,可以省略 new 关键字创建对象
  static of(value) {
    return new Container(value)
  }

  constructor(value) {
    this._value = value
  }

   // map 方法,传入变形关系,将容器里的每一个值映射到另一个容器
   map(fn) {
     return Container.of(fn(this._value)
   }
}

// 测试
const r = Container.of(3)
			.map(x => x + 2)
			.map(x => x * x)
  • 总结

    • 函数式编程的运算不直接操作值,而是由函子完成
    • 函子就是一个实现了 map 契约的对象
    • 我们可以把函子想象成一个盒子,这个盒子里封装了一个值
    • 想要处理盒子中的值,我们需要给盒子的 map 方法传递一个处理值的函数(纯函数),由这个函数来对值进行处理
    • 最终 map 方法返回一个包含新值的盒子(函子)
  • 在 Functor 中如果我们传入 null 或 undefined

// 值如果不小心传入了空值(副作用)
Container.of(null)
  .map(x => x.toUpperCase())
// TypeError: Cannot read property 'toUpperCase' of null

MayBe 函子

  • 我们在编程的过程中可能会遇到很多错误,需要对这些错误做响应的处理
  • MayBe 函子的作用就是可以对外部的空值情况做处理(控制副作用在允许的范围)
class MayBe {
  static of(value) {
    return new MayBe(value)
  }

  constructor(value) {
    this._value = value
  }

  // 如果对空值变形的话,直接返回值为 null 的函子
  map(fn) {
    return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this._value))
  }

   isNothing() {
     return this._value === null || this._value === undefined
   }
}

// 传入具体值
MayBe.of('Hello World')
  .map(x => x.toUpperCase())

// 传入 null 的情况
MayBe.of(null)
  .map(x => x.toUpperCase())
// => MayBe { _value: null }
  • 在 MayBe 函子中,我们很难确认是哪一步产生的控制问题,如下例:
let r = MayBe.of('hello world')
          .map(x => x.toUpperCase())
          .map(x => null)
          .map(x => x.split(' '))
// => MayBe { _value: null }

Either 函子

  • Either 两者中的任何一个,类似于 if ... else ... 的处理
  • 异常会让函数变的不纯,Either 函子可以用来做异常处理
class Left {
  static of(value) {
    return new Left(value)
  }

  constructor(value) {
    this._value = value
  }

  map(fn) {
   return this
  }
}


class Right {
  static of(value) {
    return new Right(value)
  }

  constructor(value) {
    this._value = value
  }

  map(fn) {
    return Right.of(fn(this._value))
  }
}
  • Either 用来处理异常
function parseJSON(json) {
  try {
    return Right.of(JSON.parse(json))
  } catch(e) {
    return Left.of({ error: e.message })
  }
}

let r = parseJSON('{ "name": "zs" }')
           .map(x => x.name.toUpperCase())
console.log(r)

IO 函子

  • IO 函子中的 _value 是一个函数,这里是把函数作为值来处理
  • IO 函子可以把不纯的动作存储到 _value 中,延迟执行这个不纯的操作(惰性执行),保证当前的操作纯
  • 把不纯的操作交给调用者来处理
const fp = require('lodash/fp')

class IO {
  static of {
    return new IO(function() {
      return x
	})
  }

  constructor(fn) {
    this._value = fn
  }

  map(fn) {
    // 把当前的 value 和传入的 fn 组合成一个新的函数
	return new IO(fp.flowRight(fn, this._value))
  }
}

// 调用
let io = IO.of(process).map(p => p.execPath)
console.log(io._value())

Task 异步执行

  • 异步任务的实现过于复杂,我们使用 folktable 中的 Task 来演示
  • folktable 是一个标准的函数式编程库
    • 和 lodash、ramda 不同的是,他没有提供很多功能函数
    • 只提供了一些函数式处理的操作,例如:compose、curry 等,一些函子 Task、Either、MayBe 等
const { comose, curry } = require('folktable/core/lambda')
const { toUpper, first } = require('lodash/fp')

// 第一个参数是参入函数的参数个数
let f = curry(2, function(x, y) {
  console.log(x + y)
})
f(3, 4)
f(3)(4)

// 函数组合
let f = compose(toUpper, first)
f(['one', 'two'])
  • Task 异步执行

    • folktable(2.3.2) 2.x 中的 Task 和 1.0 中的 Task 区别很大,1.0 中的用法更接近我们现在演示的函子
      这里以 2.3.2 来演示
const { task } = require('folktable/concurrency/task')

function readFile(filename) {
  return task(resolver => {
    fs.readFile(filename, 'utf-8', (err, data) => {
      if (err) resolver.reject(err)
	  resolver.resolve(data)
	})
  })
}

// 调用 run 执行
readFile('package.json')
  .map(split('\n'))
  .map(find(x => x.includes('version')))
  .run()
  .listen({
    onRejected: err => {
      console.log(err)
	},
	onResolved: value => {
      console.log(value)
	}
  })

Pointed 函子

  • Pointed 函子是实现了 of 静态方法的函子
  • of 方法是为了避免使用 new 来创建对象,更深层的含义是 of 方法用来把值放到上下文 Context (把值放到容器中,使用 map 来处理值)

image

class Container {
  static of(value) {
    return new Container(value)
  }
  ......
}

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

Monad(单子)

在使用 IO 函子的时候,如果我们写出如下代码:

// IO 函子的问题
const fs = require('fs')
const fp = require('lodash/fp')

let readFile = function(filename) {
  return new IO(function() {
    return fs.readFileSync(filename, 'utf-8')
  })
}

let print = function(x) {
  return new IO(function() {
    cosnole.log(x)
	return x
  })
}

// IO(IO(X))
let cat = fp.flowRight(print, readFile)
// 调用
let r = cat('package.json')._value()._value()
console.log(r)
  • Monad 函子是可以变扁的 Pointed 函子,IO(IO(X))
  • 一个函子如果具有 join 和 of 两个方法并遵守一些定律就是一个 Monad
const fs = require('fs')
const fp = require('lodash/fp')

class IO {
  static of (value) {
    return new IO(function () {
      return value
    })
  }

  constructor (fn) {
    this._value = fn
  }

  map (fn) {
    return new IO(fp.flowRight(fn, this._value))
  }

  join () {
    return this._value()
  }

  flatMap (fn) {
    return this.map(fn).join()
  }
}

let readFile = function (filename) {
  return new IO(function () {
    return fs.readFileSync(filename, 'utf-8')
  })
}

let print = function (x) {
  return new IO(function () {
    console.log(x)
    return x
  })
}

let r = readFile('package.json')
          // .map(x => x.toUpperCase())
          .map(fp.toUpper)
          .flatMap(print)
          .join()

console.log(r)

附录

posted @   小小紫苏  阅读(131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示