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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.