Skip to main content

map

Function map 

Source
pub fn map<'a, Brand: Kind_cdc7cd43dac7585f, A: 'a, B: 'a, FA, Marker>(
    f: impl FunctorDispatch<'a, Brand, A, B, FA, Marker>,
    fa: FA,
) -> <Brand as Kind_cdc7cd43dac7585f>::Of<'a, B>
Expand description

Maps a function over the values in a functor context.

Dispatches to either Functor::map or RefFunctor::ref_map based on the closure’s argument type:

  • If the closure takes owned values (Fn(A) -> B) and the container is owned, dispatches to Functor::map.
  • If the closure takes references (Fn(&A) -> B) and the container is borrowed (&fa), dispatches to RefFunctor::ref_map.

The Marker and FA type parameters are inferred automatically by the compiler from the closure’s argument type and the container argument. Callers write map::<Brand, _, _, _, _>(...) and never need to specify Marker or FA explicitly.

The dispatch is resolved at compile time with no runtime cost.

§Type Signature

forall Brand A B. Functor Brand => (A -> B, Brand A) -> Brand B

§Type Parameters

  • 'a: The lifetime of the values.
  • Brand: The brand of the functor.
  • A: The type of the value(s) inside the functor.
  • B: The type of the result(s) of applying the function.
  • FA: The container type (owned or borrowed), inferred from the argument.
  • Marker: Dispatch marker type, inferred automatically.

§Parameters

  • f: The function to apply to the value(s) inside the functor.
  • fa: The functor instance (owned for Val, borrowed for Ref).

§Returns

A new functor instance containing the result(s) of applying the function.

§Examples

use fp_library::{
	brands::*,
	functions::explicit::*,
	types::*,
};

// Owned: dispatches to Functor::map
let y = map::<OptionBrand, _, _, _, _>(|x: i32| x * 2, Some(5));
assert_eq!(y, Some(10));

// By-ref: dispatches to RefFunctor::ref_map
let lazy = RcLazy::pure(10);
let mapped = map::<LazyBrand<RcLazyConfig>, _, _, _, _>(|x: &i32| *x * 2, &lazy);
assert_eq!(*mapped.evaluate(), 20);