Expand description
Functors and monads in Rust
Functors
The following traits are provided to describe functors:
Functoris a generic trait that provides anfmapmethod, which is a generalization ofOption::map,Result::map, and so on, and which is implemented for a variety of types in the standard library.FunctorSelfis a special case ofFunctorwhere types aren’t changed when mapping. It must be implemented for everyFunctorand it must be added as a bound when mapping a type to itself.FunctorInneris a helper trait, which is automatically implemented through a blanket implementation. It provides theFunctorInner::FmapIntype, which is passed to thefmapmethod.FunctorMutis a special case ofFunctorSelfwhosefmap_mutmethod operates on&mut self. It is not implemented automatically, but this crate provides implementations for all types in the standard library for whichFunctoris 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.
Contravariant(akin toFunctor)ContravariantSelf(akin toFunctorSelf)ContravariantInner(akin toFunctorInner)ContravariantMut(akin toFunctorMut)
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
- Contravariant functor (e.g.
Writer<B>which can be converted intoWriter<A>by providing anFnMut(A) -> Btormap) - Automatically implemented helper trait providing the
RmapOuttype - Same as
ContravariantSelfbut works on&mut self - Generic type (e.g.
T<A>) whose inner type can be mapped (e.g. resulting inT<B>) - Automatically implemented helper trait providing the
FmapIntype - Same as
FunctorSelfbut works on&mut self - A
Functorthat can be mapped to itself (when providing anFnMut(Self::FmapInOut) -> Self::FmapInOut) - A
Functorthat is also a monad - Nested monad that can be joined
Functions
- Generic implementation of
Functor::fmapforMonads