rec_for_each

Macro rec_for_each 

Source
macro_rules! rec_for_each {
    ($in_list:expr, $($func:tt)*) => { ... };
}
Expand description

Helper for writing const fn equivalents of NList::for_each

This macro acts like a function with this signature:

use nlist::{NList, PeanoInt};

use nlist::receiver::Receiver;

fn rec_for_each<'a, P, T, L, F>(list: P , func: F) -> ()
where
    P: Receiver<'a, NList<T, L>>,
    L: PeanoInt,
    T: 'a,
    F: FnOnce(
        ... // parameter types explained below
    ) -> ()

The 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>)

§Example

§By value

Example that takes an NList by value

use nlist::{NList, Peano, PeanoInt, nlist};
 
const SUM: u128 = {
    let mut sum = 0;
    add_to(&mut sum, nlist![3, 5, 8]);
    sum
};
 
assert_eq!(SUM, 16);
 
const fn add_to<L>(mutator: &mut u128, list: NList<u128, L>)
where
    L: PeanoInt
{
    nlist::rec_for_each!{list, |elem: u128, next| { 
        *mutator += elem;
        add_to(mutator, next)
    }}
}

§By reference

Example that takes an NList by reference

use nlist::{NList, Peano, PeanoInt, nlist};
 
const SUM: u128 = {
    let mut sum = 0;
    add_to(&mut sum, &nlist![3, 5, 8]);
    sum
};
 
assert_eq!(SUM, 16);
 
const fn add_to<L>(mutator: &mut u128, list: &NList<u128, L>)
where
    L: PeanoInt
{
    nlist::rec_for_each!{list, |elem: &u128, next| { 
        *mutator += *elem;
        add_to(mutator, next)
    }}
}