Crate fmap

source ·
Expand description

Functors and monads in Rust

Functors

The following traits are provided to describe functors:

  • Functor is a generic trait that provides an fmap method, which is a generalization of Option::map, Result::map, and so on, and which is implemented for a variety of types in the standard library.
  • FunctorSelf is a special case of Functor where types aren’t changed when mapping. It must be implemented for every Functor and it must be added as a bound when mapping a type to itself.
  • FunctorInner is a helper trait, which is automatically implemented through a blanket implementation. It provides the FunctorInner::FmapIn type, which is passed to the fmap method.
  • FunctorMut is a special case of FunctorSelf whose fmap_mut method operates on &mut self. It is not implemented automatically, but this crate provides implementations for all types in the standard library for which Functor is implemented.

Contravariant functors

The following traits are provided to describe contravariant functors, e.g. a Writer<B> that can be converted to a Writer<A> using an Fn(A) -> B.

Monads

The Monad trait describes functors which are also monads. Its supertrait Pure allows wrapping a single value. (Pure::pure is equivalent to what’s usually called “return” in the context of monads). The method Monad::bind is a generalization of Option::and_then and Result::and_then. Nested monads automatically implement NestedMonad and can be joined with NestedMonad::mjoin.

Traits

Functions