rf_core/lang/builtins.rs
1use crate::lang::{foldhood, mid, nbr};
2use crate::vm::round_vm::RoundVM;
3use std::str::FromStr;
4
5/// Evaluates the given expressions and returns the result based on the given condition.
6/// N.B both th and el will be evaluated, thus they will both affect the [Path], but only the result of one of them will be returned.
7///
8/// # Arguments
9/// * `vm` - The current VM.
10/// * `cond` - The condition to evaluate, which should return a boolean.
11/// * `th` - The then-expression to evaluate.
12/// * `el` - The else-expression to evaluate.
13///
14/// # Returns
15/// The result of the evaluation of the then-expression if the condition is true, else the result of the evaluation of the else-expression alongside the RoundVM.
16pub fn mux<A, C, TH, EL>(vm: &mut RoundVM, cond: C, th: TH, el: EL) -> A
17where
18 C: Fn(&mut RoundVM) -> bool,
19 TH: Fn(&mut RoundVM) -> A,
20 EL: Fn(&mut RoundVM) -> A,
21{
22 let flag = cond(vm);
23 let th_val = th(vm);
24 let el_val = el(vm);
25 if flag {
26 th_val
27 } else {
28 el_val
29 }
30}
31
32/// Performs a foldhood on the given expression, excluding self from the aligned neighbors.
33///
34/// # Arguments
35///
36/// * `vm` the current VM
37/// * `init` the initial value
38/// * `aggr` the function to apply to the value
39/// * `expr` the expression to evaluate
40///
41/// # Generic Parameters
42///
43/// * `A` The type of value returned by the expression.
44/// * `F` - The type of init, which must be a closure that takes no arguments and returns a value of type `A`.
45/// * `G` - The type of aggr, which must be a closure that takes a tuple `(A, A)` and returns a value of type `A`.
46/// * `H` - The type of expr, which must be a closure that takes a `RoundVM` as argument and returns a tuple `(RoundVM, A)`.
47///
48/// # Returns
49///
50/// the aggregated value
51pub fn foldhood_plus<A: Copy + 'static + FromStr, F, G, H>(
52 vm: &mut RoundVM,
53 init: F,
54 aggr: G,
55 expr: H,
56) -> A
57where
58 F: Fn(&mut RoundVM) -> A + Copy,
59 G: Fn(A, A) -> A,
60 H: Fn(&mut RoundVM) -> A + Copy,
61{
62 foldhood(vm, init, aggr, |vm1| {
63 let self_id = mid(vm1);
64 let nbr_id = nbr(vm1, mid);
65 mux(vm1, |_vm2| self_id == nbr_id, init, expr)
66 })
67}