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 is automatically implemented through a blanket implementation and it must be added as a bound when mapping a type to itself.
  • 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.

Pinned boxed Futures are also monads. The bind method will call the given closure on completion of the future.

Note: This implementation doesn’t require Future::Output to be a Result and it will thus not short-circuit when a Result::Err is returned. Therefore, it rather behaves like .then (instead of .and_then) on futures.

Nested monads automatically implement NestedMonad and can be joined with NestedMonad::mjoin, which is equivalent to .bind(|x| x).

Traits

Functions