ksl 0.1.30

KSL core library and interpreter
Documentation
//! # ksl::builtin::reduce
//!
//! Built-in function `Reduce`.

use crate::{Environment, builtin::eval_builtin, eval::apply::eval_apply, value::Value};

pub(crate) fn builtin(args: &[Value], env: Environment) -> Result<Value, std::sync::Arc<str>> {
    if let [list, func, init] = args {
        match eval_apply(list, env.clone())? {
            Value::List(elements) => {
                if elements.is_empty() {
                    eval_apply(init, env)
                } else {
                    let mut reduced = eval_apply(init, env.clone())?;
                    let func = std::sync::Arc::new(eval_apply(func, env.clone())?);
                    for element in elements.iter() {
                        reduced = match func.as_ref() {
                            Value::Builtin(name) => eval_builtin(name, &[reduced, element.clone()], env.clone()),
                            Value::Lambda(_, _, _) | Value::Plugin(_, _) => eval_apply(
                                &Value::Apply(vec![reduced, element.clone()], func.clone()),
                                env.clone(),
                            ),
                            e => {
                                return Err(std::sync::Arc::from(format!(
                                    concat!("Error[ksl::builtin::Reduce]: ", "Unexpected value: `{}`."),
                                    e
                                )));
                            }
                        }?;
                    }
                    Ok(reduced)
                }
            }
            e => Err(std::sync::Arc::from(format!(
                concat!("Error[ksl::builtin::Reduce]: ", "Unexpected value: `{}`."),
                e
            ))),
        }
    } else {
        Err(std::sync::Arc::from(format!(
            concat!(
                "Error[ksl::builtin::Reduce]: ",
                "Expected 3 parameters, but {} were passed."
            ),
            args.len()
        )))
    }
}