Skip to main content

rl_lang/interpreter/stdlib/array/
arr_reduce.rs

1use crate::{
2    interpreter::{evaluator::Evaluator, values::Value},
3    utils::{errors::Error, span::Span},
4};
5
6pub fn std_arr_reduce(
7    eval: &mut Evaluator,
8    array: Value,
9    function: Value,
10    initial: Value,
11    span: Span,
12) -> Result<Value, Error> {
13    let items = match array {
14        Value::Values { items, .. } => items,
15        other => {
16            return Err(eval.err(
17                format!(
18                    "arr_reduce() accepts only arrays, found {}",
19                    other.type_name()
20                ),
21                span,
22            ));
23        }
24    };
25
26    if !matches!(function, Value::Function { .. }) {
27        return Err(eval.err(
28            format!(
29                "arr_reduce() expected function or lambda, found {}",
30                function.type_name()
31            ),
32            span,
33        ));
34    }
35
36    let mut result = initial;
37
38    for item in items {
39        result = eval.call_value(function.clone(), vec![result, item], span)?;
40    }
41
42    Ok(result)
43}