Skip to content

函子 (Functor)

函子可以理解为一种带有 map 方法的容器。它的核心思想是:把函数应用到容器内部的值上,但不直接暴露或修改容器内部的值,而是返回一个新的容器。

简单容器 Container

js
class Container {
	constructor(value) {
		this._value = value;
	}

	static of(value) {
		return new Container(value);
	}

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

const result = Container.of(5)
	.map(x => x + 2) // Container(7)
	.map(x => x * x); // Container(49)

console.log(result._value); // 49

Maybe 函子 — 处理空值的优雅方式

Maybe 用于在可能为 nullundefined 的值上安全地链式调用函数,避免抛出异常:

js
class Maybe {
	constructor(value) {
		this._value = value;
	}

	static of(value) {
		return new Maybe(value);
	}

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

	map(fn) {
		return this.isNothing() ? Maybe.of(null) : Maybe.of(fn(this._value));
	}
}

const user1 = { name: "Alice", address: { city: "New York" } };
const user2 = { name: "Bob" };

const getCityUpperCase = (user) =>
	Maybe.of(user)
		.map(u => u.address)
		.map(a => a.city)
		.map(c => c.toUpperCase());

console.log(getCityUpperCase(user1)._value); // "NEW YORK"
console.log(getCityUpperCase(user2)._value); // null

小结

  • 函子使得在“容器化”的值上进行函数应用变得安全且可组合。
  • 常见的函子还有 EitherIOTask/Promise 等,分别用于处理错误、延迟/副作用、异步等场景。

MIT Licensed | Keep Learning.