Optics: classy optics
Tutorial Video
Text description (accessibility)
This video demonstrates the "Optics: classy optics" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Optics are composable data accessors originating from Haskell's lens library (Edward Kmett, 2012). Key difference from OCaml: 1. **HKT requirement**: Haskell's van Laarhoven encoding uses Functor/Applicative for optic unification requiring HKT; Rust uses explicit struct types per optic kind.
Tutorial
The Problem
Optics are composable data accessors originating from Haskell's lens library (Edward Kmett, 2012). They solve the deeply-nested update problem in immutable data: updating a field three levels deep requires rebuilding all intermediate values. Optics compose — a lens into a struct field composed with a prism for an enum variant gives a combined accessor that can get, set, and modify deeply nested optional values. The optic hierarchy includes Lens (exactly one focus), Prism (zero or one focus on enum variants), Traversal (zero or more foci), and Iso (lossless bidirectional conversion).
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! # Classy Optics
//! Type-class based optics.
pub trait HasName {
fn name(&self) -> &str;
fn set_name(&mut self, n: String);
}
#[derive(Clone)]
pub struct User {
pub name: String,
}
impl HasName for User {
fn name(&self) -> &str {
&self.name
}
fn set_name(&mut self, n: String) {
self.name = n;
}
}
pub fn greet(x: &impl HasName) -> String {
format!("Hello, {}!", x.name())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_classy() {
let u = User { name: "Bob".into() };
assert_eq!(greet(&u), "Hello, Bob!");
}
}Key Differences
^., .~, %~ for terse optic use; Rust uses method calls, more verbose but explicit.lens-rs and similar crates provide derive macros for automatic lens generation; OCaml uses ppx_lens for the same.OCaml Approach
OCaml optics use the same record-with-function approach:
type ('s, 'a) lens = { get: 's -> 'a; set: 's -> 'a -> 's }
let name_lens = { get = (fun u -> u.name); set = (fun u n -> { u with name = n }) }
let compose l1 l2 = { get = (fun s -> l2.get (l1.get s)); set = (fun s a -> l1.set s (l2.set (l1.get s) a)) }
Full Source
#![allow(clippy::all)]
//! # Classy Optics
//! Type-class based optics.
pub trait HasName {
fn name(&self) -> &str;
fn set_name(&mut self, n: String);
}
#[derive(Clone)]
pub struct User {
pub name: String,
}
impl HasName for User {
fn name(&self) -> &str {
&self.name
}
fn set_name(&mut self, n: String) {
self.name = n;
}
}
pub fn greet(x: &impl HasName) -> String {
format!("Hello, {}!", x.name())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_classy() {
let u = User { name: "Bob".into() };
assert_eq!(greet(&u), "Hello, Bob!");
}
}#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_classy() {
let u = User { name: "Bob".into() };
assert_eq!(greet(&u), "Hello, Bob!");
}
}
Deep Comparison
Classy Optics
Trait-based field access