Skip to main content

while_some

Function while_some 

Source
pub fn while_some<'a, Brand: MonadRec, A: Monoid + Clone + 'a>(
    action: impl Fn() -> <Brand as Kind_cdc7cd43dac7585f>::Of<'a, Option<A>> + 'a,
) -> <Brand as Kind_cdc7cd43dac7585f>::Of<'a, A>
Expand description

Repeatedly runs a monadic action, accumulating results while it returns Some.

Executes action in a loop. When action returns Some(a), the value a is accumulated via Semigroup::append. When action returns None, the accumulated value is returned. The accumulator starts at Monoid::empty().

This function is stack-safe via tail_rec_m.

§Type Signature

forall Brand A. (MonadRec Brand, Monoid A) => (() -> Brand (Option A)) -> Brand A

§Type Parameters

  • 'a: The lifetime of the computation.
  • Brand: The brand of the monad.
  • A: The type of the accumulated value, which must implement Monoid and Clone.

§Parameters

  • action: A closure that produces a monadic Option<A> each iteration.

§Returns

The accumulated monoidal value once action returns None.

§Examples

use {
	fp_library::{
		brands::*,
		functions::*,
	},
	std::cell::Cell,
};

// Accumulate strings until None
let items =
	vec![Some("hello".to_string()), Some(" ".to_string()), Some("world".to_string()), None];
let idx = Cell::new(0usize);
let result = while_some::<OptionBrand, _>(|| {
	let i = idx.get();
	idx.set(i + 1);
	Some(items[i].clone())
});
assert_eq!(result, Some("hello world".to_string()));