Trait fmap::Applicative
source · pub trait Applicative<'a, B>where
Self: Pure<'a, B> + Pure<'a, BoxMapper<'a, Self, B>>,
B: 'a,{
// Required method
fn apply(
self,
f: <Self as Functor<'a, BoxMapper<'a, Self, B>>>::Mapped
) -> <Self as Functor<'a, B>>::Mapped;
}
Expand description
An applicative Functor
Note: In functional programming, every monad is also an applicative
functor. The Monad
trait, however, does not have Applicative
as
superclass, because it is not possible to provide a corresponding
Applicative
implementation for every monad. The reason is that (unlike in
functional programming) values in Rust may be moved and only used once. The
Applicative
implementation for Vec<A>
demands A: Clone
, for example,
while the Monad
implementation for Vec<A>
does not put any bounds on
A
. The requirements for a monad to be able to implement
Applicative::apply
through monad_apply
are:
- The monad must have a lifetime of
'a
. - The monad must be
Send
. - The monad must be
Clone
. - The monad must support a boxed mapper as inner value (which is the
case when it implements the
MonadWithMapper
trait).
Examples
use fmap::Applicative;
let f: Vec<Box<dyn Send + FnMut(i32) -> i32>> =
vec![Box::new(|x| x), Box::new(|x| x * 100)];
let a = vec![4, 7, 9];
let b = a.apply(f);
assert_eq!(b, vec![4, 7, 9, 400, 700, 900]);