Yoneda Lemma
Tutorial Video
Text description (accessibility)
This video demonstrates the "Yoneda Lemma" functional Rust example. Difficulty level: Expert. Key concepts covered: Functional Programming. The Yoneda lemma is one of the most important results in category theory: `Nat(Hom(A, -), F) ≅ F(A)`. Key difference from OCaml: 1. **Rank
Tutorial
The Problem
The Yoneda lemma is one of the most important results in category theory: Nat(Hom(A, -), F) ≅ F(A). In Rust terms: a natural transformation from fn(A, -) to any functor F is in one-to-one correspondence with a value of F(A). The practical consequence: Yoneda<F, A> — a type holding a natural transformation — is isomorphic to F(A> but enables free map operations without actually running them, accumulating a composition chain that is applied all at once.
🎯 Learning Outcomes
Yoneda<F, A> defers and fuses map operations (Yoneda's performance benefit)to_yoneda(fa)(id) = fa and from_yoneda(y) = y(id)Functor instances: any type with a Yoneda wrapper gets map for freeCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
'b. record polymorphism expresses Yoneda directly; Rust requires defunctionalization (GAT markers).Yoneda provides a free Functor instance for any type constructor — even non-functors can be mapped over via Yoneda lifting.OCaml Approach
OCaml's Yoneda:
type ('f, 'a) yoneda = { run : 'b. ('a -> 'b) -> 'b 'f }
let to_yoneda fa = { run = fun f -> map f fa }
let from_yoneda y = y.run Fun.id
let map_yoneda f y = { run = fun g -> y.run (g >> f) }
map_yoneda fuses the function f into the natural transformation without actually running it. OCaml's rank-2 type 'b. enables the polymorphic run field.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Yoneda Lemma
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
to_yoneda and from_yoneda for Option<A> and verify the round-trip: from_yoneda(to_yoneda(fa)) == fa.map operations via Yoneda and verify only one actual traversal occurs.to_yoneda(from_yoneda(y)) == y for a specific y.