macro_rules! rec_fold {
($in_list:expr, $accum:expr, $($func:tt)*) => { ... };
}Expand description
Helper for writing const fn equivalents of NList::fold
This macro acts like a function with this signature:
use nlist::{NList, PeanoInt};
use nlist::receiver::Receiver;
fn rec_fold<'a, P, T, L, F, U>(list: P , accum: U, func: F) -> U
where
P: Receiver<'a, NList<T, L>>,
L: PeanoInt,
T: 'a,
F: FnOnce(
... // parameter types explained below
) -> UThe closure is only called when the list is non-empty (i.e.: when L != 0).
The closure parameters depend on the value of P:
- If
P == NList<T, L>: the parameters are(T, Nlist<T, L::SubOneSat>) - If
P == &NList<T, L>: the parameters are(&T, &Nlist<T, L::SubOneSat>) - If
P == &mut NList<T, L>: the parameters are(&mut T, &mut Nlist<T, L::SubOneSat>)
§Accumulator Argument
The accum argument is only evaluated if the list is empty,
which means that you can pass it by value and still use it in the passed in closure.
§Example
§By value
Example that takes an NList by value
use nlist::{NList, Peano, PeanoInt, nlist};
const SUM: u128 = add_up(0, nlist![1, 2, 3, 4, 5]);
assert_eq!(SUM, 15);
const fn add_up<L>(sum: u128, list: NList<u128, L>) -> u128
where
L: PeanoInt
{
nlist::rec_fold!{list, sum, |elem: u128, next| add_up(sum + elem, next)}
}§By reference
Example that takes an NList by reference
use nlist::{NList, Peano, PeanoInt, nlist};
const SUM: u128 = add_up(0, &nlist![3, 5, 8]);
assert_eq!(SUM, 16);
const fn add_up<L>(sum: u128, list: &NList<u128, L>) -> u128
where
L: PeanoInt
{
nlist::rec_fold!{list, sum, |elem: &u128, next| add_up(sum + *elem, next)}
}