跳到主要内容

范畴与半群胚

编程中的范畴由什么组成?​

  • 对象: 通常对应类型;
  • 态射: 对象之间的关系,通常对应函数;
  • 目标: 研究结构如何组合,而不依赖对象内部细节;

合法范畴必须满足哪些规则?​

  1. 恒等: 每个对象 A 都有 id :: A -> A;
  2. 可组合: f :: A -> B 与 g :: B -> C 能组成 g ∘ f;
  3. 结合律: f ∘ (g ∘ h) = (f ∘ g) ∘ h;
class Max {
constructor(value) {
this.value = value;
}
id() {
return this;
}
compose(other) {
return this.value > other.value ? this : other;
}
}

new Max(2).compose(new Max(3)).compose(new Max(5)).id().value; // 5

半群胚与范畴相差哪条规则?​

  • 半群胚(Semigroupoid): 对象与态射可以按结合律组合;
  • 缺少保证: 不要求每个对象都存在恒等态射;
  • 关系: 每个范畴都是半群胚,反向不一定成立;
const Semigroupoid = (fn) => ({
run: fn,
compose: (other) => Semigroupoid((x) => fn(other.run(x))),
});

const upper = Semigroupoid((s) => s.toUpperCase());
const exclaim = Semigroupoid((s) => `${s}!`);
exclaim.compose(upper).run("hello"); // HELLO!

为什么范畴论关注组合?​

  • 抽象层: 只依赖恒等与组合规律,不依赖具体数据表示;
  • 迁移性: 同一组合推理可用于函数、数据结构和其他满足规律的系统;