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 is automatically implemented through a blanket implementation and it must be added as a bound when mapping a type to itself.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)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.
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
- Contravariant functor (e.g.
Writer<B>which can be converted intoWriter<A>by providing anFnMut(A) -> Btocontramap) - Same as
ContravariantSelfbut works on&mut self - A
Contravariantfunctor that can be mapped to itself (when providing anFnMut(Self::Inner) -> Self::Inner) - Generic type (e.g.
T<A>) whose inner type can be mapped (e.g. resulting inT<B>) - Same as
Functorbut works on&mut self - A
Functorthat can be mapped to itself (when providing anFnMut(Self::Inner) -> Self::Inner) - A
Functorthat is also a monad - Nested monad that can be joined
Functions
- Generic implementation of
Functor::fmapforMonads