ExamplesBy LevelBy TopicLearning Paths
618 Expert

Optics: traversal optics

Functional Programming

Tutorial Video

Text description (accessibility)

This video demonstrates the "Optics: traversal optics" functional Rust example. Difficulty level: Expert. 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

  • • The specific optic demonstrated in this example and what it focuses on
  • • How to implement the optic manually using closures or structs in Rust
  • • How this optic composes with others in the hierarchy
  • • The laws the optic must satisfy for correct behavior
  • • Where optics are used: state management, config manipulation, nested data transformation
  • Code Example

    #![allow(clippy::all)]
    //! # Traversal Optics
    //! Focus on multiple elements.
    
    pub fn traverse_vec<A: Clone, B>(xs: &[A], f: impl Fn(&A) -> Option<B>) -> Option<Vec<B>> {
        xs.iter().map(f).collect()
    }
    
    pub fn over_all<A: Clone>(xs: &mut [A], f: impl Fn(&A) -> A) {
        for x in xs.iter_mut() {
            *x = f(x);
        }
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn test_traverse() {
            let xs = vec![1, 2, 3];
            let result = traverse_vec(&xs, |x| Some(x * 2));
            assert_eq!(result, Some(vec![2, 4, 6]));
        }
    }

    Key Differences

  • HKT requirement: Haskell's van Laarhoven encoding uses Functor/Applicative for optic unification requiring HKT; Rust uses explicit struct types per optic kind.
  • Operator syntax: Haskell uses ^., .~, %~ for terse optic use; Rust uses method calls, more verbose but explicit.
  • Derive macros: lens-rs and similar crates provide derive macros for automatic lens generation; OCaml uses ppx_lens for the same.
  • Performance: Boxed closure implementations have runtime overhead; monomorphized generic versions compile to zero-cost abstractions.
  • 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)]
    //! # Traversal Optics
    //! Focus on multiple elements.
    
    pub fn traverse_vec<A: Clone, B>(xs: &[A], f: impl Fn(&A) -> Option<B>) -> Option<Vec<B>> {
        xs.iter().map(f).collect()
    }
    
    pub fn over_all<A: Clone>(xs: &mut [A], f: impl Fn(&A) -> A) {
        for x in xs.iter_mut() {
            *x = f(x);
        }
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn test_traverse() {
            let xs = vec![1, 2, 3];
            let result = traverse_vec(&xs, |x| Some(x * 2));
            assert_eq!(result, Some(vec![2, 4, 6]));
        }
    }
    ✓ Tests Rust test suite
    #[cfg(test)]
    mod tests {
        use super::*;
        #[test]
        fn test_traverse() {
            let xs = vec![1, 2, 3];
            let result = traverse_vec(&xs, |x| Some(x * 2));
            assert_eq!(result, Some(vec![2, 4, 6]));
        }
    }

    Deep Comparison

    Traversal

    Focus on zero or more elements

    Exercises

  • Lens laws: Write tests for all three lens laws: get-set (get after set returns set value), set-get (set to current value is identity), set-set (second set wins).
  • Prism laws: Write tests for prism laws: preview after review returns Some, set via review then preview round-trips.
  • Compose two levels: Create a lens for a struct field and a prism for an enum variant in that field — compose them and modify the inner value when the variant is present.
  • Open Source Repos