pub trait Bind<'a, A: 'a>: Functor<'a, A> {
fn bind<B: 'a, F>(self, f: F) -> Self::Target<B>
where
F: Fn(A) -> Self::Target<B> + 'a;
fn into_stream(self) -> (Self::Target<()>, LocalBoxStream<'a, A>)
where
Self: Sized,
Self::Target<()>: Pure<()>,
{ ... }
}
Expand description
Bind
lets you chain computations together.
It takes a function Fn(A) -> M<B>
and applies it to the A
inside M<A>
.
You can think of this as a callback function for when the value of A
is
ready to be processed, returning the next computation in the sequence.
This is the primary component of the dreaded Monad
trait,
but to be a Monad
a type must also implement
Applicative
, which in turn requires implementations
for Functor
, Pure
and
Apply
.
Required Methods§
sourcefn bind<B: 'a, F>(self, f: F) -> Self::Target<B>where
F: Fn(A) -> Self::Target<B> + 'a,
fn bind<B: 'a, F>(self, f: F) -> Self::Target<B>where
F: Fn(A) -> Self::Target<B> + 'a,
Apply the function f
to the A
or A
s inside the M<A>
to turn it
into an M<B>
.
Think of this as a way to chain two computations together: f
can be
seen as a callback function for a computation: m.bind(|result| { ... })
means “run m
and call this function when the result is ready.” The
return value from f
, of type M<B>
, is effectively the original
computation, M<A>
, followed by the M<B>
from the callback function
when the result of M<A>
is ready.
Provided Methods§
sourcefn into_stream(self) -> (Self::Target<()>, LocalBoxStream<'a, A>)where
Self: Sized,
Self::Target<()>: Pure<()>,
fn into_stream(self) -> (Self::Target<()>, LocalBoxStream<'a, A>)where
Self: Sized,
Self::Target<()>: Pure<()>,
Turn an M<A>
into an M<()>
and a
Stream<Item = A>
that will yield values of
A
.
The values won’t start yielding until you run the M<()>
, whatever that
means for any given M
. For simple types like Result
and
Vec
, you don’t have to do anything, they’ll yield their entire
contents immediately. For effect types, you’ll need to await their
futures to get them to start yielding.
let list = vec![1, 2, 3];
let (_, mut stream) = list.into_stream();
assert_eq!(stream.next().await, Some(1));
assert_eq!(stream.next().await, Some(2));
assert_eq!(stream.next().await, Some(3));
assert_eq!(stream.next().await, None);