Skip to main content

traverse

Function traverse 

Source
pub fn traverse<'a, FnBrand, Brand: Kind_cdc7cd43dac7585f, A: 'a, B: 'a, F: Kind_cdc7cd43dac7585f, FTA, Marker>(
    func: impl TraverseDispatch<'a, FnBrand, Brand, A, B, F, FTA, Marker>,
    ta: FTA,
) -> <F as Kind_cdc7cd43dac7585f>::Of<'a, <Brand as Kind_cdc7cd43dac7585f>::Of<'a, B>>
Expand description

Traverses a structure, mapping each element to a computation and combining the results.

Dispatches to either Traversable::traverse or RefTraversable::ref_traverse based on the closure’s argument type:

  • If the closure takes owned values (Fn(A) -> F::Of<B>) and the container is owned, dispatches to Traversable::traverse. The FnBrand parameter is unused but must be specified for uniformity.
  • If the closure takes references (Fn(&A) -> F::Of<B>) and the container is borrowed (&ta), dispatches to RefTraversable::ref_traverse. The FnBrand parameter is passed through as the function brand.

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

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

§Type Signature

forall Brand A B F. (Traversable Brand, Applicative F) => (A -> F B, Brand A) -> F (Brand B)

§Type Parameters

  • 'a: The lifetime of the values.
  • FnBrand: The brand of the cloneable function to use.
  • Brand: The brand of the traversable structure.
  • A: The type of the elements in the input structure.
  • B: The type of the elements in the output structure.
  • F: The applicative functor brand.
  • FTA: The container type (owned or borrowed), inferred from the argument.
  • Marker: Dispatch marker type, inferred automatically.

§Parameters

  • func: The function to apply to each element, returning a value in an applicative context.
  • ta: The traversable structure (owned for Val, borrowed for Ref).

§Returns

The structure wrapped in the applicative context.

§Examples

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

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

// By-ref: dispatches to RefTraversable::ref_traverse
let y = traverse::<RcFnBrand, OptionBrand, _, _, OptionBrand, _, _>(
	|x: &i32| Some(*x * 2),
	&Some(5),
);
assert_eq!(y, Some(Some(10)));