Using the functor pattern

A functor is approximately the inverse of a function:

  • A function defines a transformation, accepts data, and returns the result of the transformation
  • A functor defines data, accepts a function, and returns the result of the transformation

A simple example of a functor is the Rust vector and its accompanying map function:

fn main() {   let m: Vec<u64> = vec![1, 2, 3];   let n: Vec<u64> = m.iter().map(|x| { x*x }).collect();   println!("{:?}", m);   println!("{:?}", n);}

Functors are often thought of as only the map function, due to the rules of what constitutes a functor or not. The preceding common case is what's called a structure-preserving map. Functors do not need to be structure-preserving. For example, take the very ...

Get Hands-On Functional Programming in Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.