Optics: lens pattern
Tutorial Video
Text description (accessibility)
This video demonstrates the "Optics: lens pattern" functional Rust example. Difficulty level: Fundamental. 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)]
//! # Lens Pattern
//! Focus on a field within a struct.
#[derive(Clone, Debug)]
pub struct Address {
pub city: String,
pub zip: String,
}
#[derive(Clone, Debug)]
pub struct User {
pub name: String,
pub addr: Address,
}
pub fn get_city(u: &User) -> &str {
&u.addr.city
}
pub fn set_city(u: &User, city: String) -> User {
User {
addr: Address {
city,
..u.addr.clone()
},
..u.clone()
}
}
pub fn modify_city(u: &User, f: impl Fn(&str) -> String) -> User {
set_city(u, f(get_city(u)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_modify() {
let u = User {
name: "Bob".into(),
addr: Address {
city: "NYC".into(),
zip: "10001".into(),
},
};
let u2 = modify_city(&u, |c| c.to_lowercase());
assert_eq!(u2.addr.city, "nyc");
}
}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)]
//! # Lens Pattern
//! Focus on a field within a struct.
#[derive(Clone, Debug)]
pub struct Address {
pub city: String,
pub zip: String,
}
#[derive(Clone, Debug)]
pub struct User {
pub name: String,
pub addr: Address,
}
pub fn get_city(u: &User) -> &str {
&u.addr.city
}
pub fn set_city(u: &User, city: String) -> User {
User {
addr: Address {
city,
..u.addr.clone()
},
..u.clone()
}
}
pub fn modify_city(u: &User, f: impl Fn(&str) -> String) -> User {
set_city(u, f(get_city(u)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_modify() {
let u = User {
name: "Bob".into(),
addr: Address {
city: "NYC".into(),
zip: "10001".into(),
},
};
let u2 = modify_city(&u, |c| c.to_lowercase());
assert_eq!(u2.addr.city, "nyc");
}
}#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_modify() {
let u = User {
name: "Bob".into(),
addr: Address {
city: "NYC".into(),
zip: "10001".into(),
},
};
let u2 = modify_city(&u, |c| c.to_lowercase());
assert_eq!(u2.addr.city, "nyc");
}
}
Deep Comparison
Lens
Get/set a field immutably