pub trait Monad<'a, B>where
Self: Pure<'a, B>,
B: 'a,{
// Required method
fn bind<F>(self, f: F) -> Self::Mapped
where F: 'a + Send + FnMut(Self::Inner) -> Self::Mapped;
}
Expand description
A Functor
that is also a monad
Note: The Monad
trait deliberately does not imply Applicative
.
See documentation on Applicative
for further information.
The method Monad::bind
is a generalization of Option::and_then
and
Result::and_then
. Pinned boxed Future
s are also monads. The bind
method will call the given closure on completion of the future. This monad
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)
.
Examples
use fmap::Monad;
let a = vec![5, 6, 7];
let b = a.bind(|x| vec![2*x, 10*x]);
assert_eq!(b, vec![10, 50, 12, 60, 14, 70]);
let a: Box<dyn Iterator<Item = i32>> = Box::new(vec![5, 6, 7].into_iter());
let b = a.bind(|x| Box::new(vec![2*x, 10*x].into_iter()));
assert_eq!(b.collect::<Vec<_>>(), vec![10, 50, 12, 60, 14, 70]);
let nested = vec![vec![1, 3], vec![2, 9, 9]];
assert_eq!(nested.bind(|x| x), vec![1, 3, 2, 9, 9]);
Note: .bind(|x| x)
is also available as NestedMonad::mjoin