pub trait Functor<'a, B>where
Self: Sized,
B: 'a,{
type Inner: 'a;
type Mapped: Functor<'a, B, Inner = B, Mapped = Self::Mapped> + Functor<'a, Self::Inner, Inner = B, Mapped = Self>;
// Required method
fn fmap<F>(self, f: F) -> Self::Mapped
where F: 'a + Send + FnMut(Self::Inner) -> B;
// Provided method
fn fmap_fn_mutref<F>(self, f: F) -> Self
where Self: FunctorSelf<'a, B>,
F: 'a + Send + FnMut(&mut Self::Inner) { ... }
}
Expand description
Generic type (e.g. T<A>
) whose inner type can be mapped (e.g. resulting
in T<B>
)
Type parameter B
specifies the new inner type after the fmap
operation.
Examples
Implementing Functor
impl<'a, A, B> Functor<'a, B> for Option<A>
where
A: 'a,
B: 'a,
{
type Inner = A;
type Mapped = Option<B>;
fn fmap<F>(self, f: F) -> Self::Mapped
where
F: 'a + Send + FnMut(Self::Inner) -> B,
{
self.map(f)
}
}
Using Functor::fmap
use fmap::Functor;
let ok: Result<i32, i32> = Ok(2);
assert_eq!(ok.fmap(|x| x + 1), Ok(3));
let err: Result<i32, i32> = Err(0);
assert_eq!(err.fmap(|x| x + 1), Err(0));
let int_vec: Vec<i32> = vec![2, 3, 5];
let float_vec: Vec<f64> = int_vec.fmap(Into::into);
assert_eq!(float_vec, vec![2.0, 3.0, 5.0]);
fn convert_inner<'a, T, A, B>(outer: T) -> T::Mapped
where
// NOTE: `A` and `B` can be different types. Where `A` and `B`
// are always the same type, `FunctorSelf` should be used.
T: Functor<'a, B, Inner = A>,
A: 'a + Into<B>,
{
outer.fmap(Into::into)
}
let int_vec2: Vec<i32> = vec![7, 11, 13];
let float_vec2: Vec<f64> = convert_inner(int_vec2);
assert_eq!(float_vec2, vec![7.0, 11.0, 13.0]);
Also see FunctorSelf
.
Required Associated Types§
sourcetype Inner: 'a
type Inner: 'a
Inner type
For any functor T<A>
, where values of type A
are passed to the
Functor::fmap
function, set Inner = A
.
Required Methods§
sourcefn fmap<F>(self, f: F) -> Self::Mappedwhere
F: 'a + Send + FnMut(Self::Inner) -> B,
fn fmap<F>(self, f: F) -> Self::Mappedwhere F: 'a + Send + FnMut(Self::Inner) -> B,
Replaces inner type and value by applying a mapping function
Where Functor::Inner
and B
are the same type, consider using
Functor::fmap_fn_mutref
or FunctorMut::fmap_mut
, which might
provide specialized implementations that are more efficient.
Provided Methods§
sourcefn fmap_fn_mutref<F>(self, f: F) -> Selfwhere
Self: FunctorSelf<'a, B>,
F: 'a + Send + FnMut(&mut Self::Inner),
fn fmap_fn_mutref<F>(self, f: F) -> Selfwhere Self: FunctorSelf<'a, B>, F: 'a + Send + FnMut(&mut Self::Inner),
Same as Functor::fmap
but uses a mapping function that takes a
mutable reference
This method has a default implementation that can be overridden if
there is a more efficient way of mapping inner values in place.
See also FunctorMut::fmap_mut
, which works on &mut self
.
For types which implement FunctorMut
and where fmap_mut
’s
implementation doesn’t use fmap_fn_mutref
, consider to provide the
following implementation:
fn fmap_fn_mutref<F>(mut self, f: F) -> Self
where
F: 'a + Send + FnMut(&mut Self::Inner),
{
self.fmap_mut(f);
self
}