use crate::js::*;
use crate::value::*;
use imbl::*;
use std::rc::Rc;

#[derive(Clone, Debug, Hash)]
pub enum BaseFn {
    Nullary(&'static str, fn() -> Value),
    Unary(&'static str, fn(&Value) -> Value),
    Binary(&'static str, fn(&Value, &Value) -> Value),
    Ternary(&'static str, fn(&Value, &Value, &Value) -> Value),
}

pub fn eq(x: &Value, y: &Value) -> Value {
    if x == y {
        Value::True
    } else {
        Value::False
    }
}

pub fn add(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => Value::Number(x + y),
        _ => unreachable!("internal Ludus error: wrong arguments to base add: {x}, {y}"),
    }
}

pub fn sub(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => Value::Number(x - y),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn unbox(x: &Value) -> Value {
    match x {
        Value::Box(cell) => cell.as_ref().borrow().clone(),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn store(b: &Value, val: &Value) -> Value {
    if let Value::Box(cell) = b {
        cell.replace(val.clone());
        val.clone()
    } else {
        unreachable!("internal Ludus error")
    }
}

// TODO: do better than returning just the docstr
// name, patterns, AND docstring
pub fn doc(f: &Value) -> Value {
    let f = f.as_fn();
    let name = f.name();
    let patterns = f.patterns();
    let docstr = f.doc();
    Value::from_string(format!(
        "{name}\n{}\n{}",
        patterns.stringify(),
        docstr.stringify()
    ))
}

pub fn assoc(dict: &Value, key: &Value, value: &Value) -> Value {
    match (dict, key) {
        (Value::Dict(d), Value::Keyword(k)) => {
            Value::Dict(Box::new(d.update(Key::Keyword(k), value.clone())))
        }
        (Value::Dict(d), Value::Interned(k)) => {
            Value::Dict(Box::new(d.update(Key::Interned(k), value.clone())))
        }
        (Value::Dict(d), Value::String(s)) => {
            Value::Dict(Box::new(d.update(Key::String(s.clone()), value.clone())))
        }
        _ => unreachable!("internal Ludus error calling assoc with ({dict}, {key}, {value})"),
    }
}

pub fn r#bool(x: &Value) -> Value {
    match x {
        Value::Nil | Value::False => Value::False,
        _ => Value::True,
    }
}

pub fn chars(x: &Value) -> Value {
    match x {
        Value::Interned(s) => {
            let mut charlist = vector![];
            for char in s.chars() {
                charlist.push_back(Value::from_string(char.to_string()))
            }
            Value::Tuple(Rc::new(vec![
                Value::Keyword("ok"),
                Value::List(Box::new(charlist)),
            ]))
        }
        Value::String(s) => {
            let mut charlist = vector![];
            for char in s.chars() {
                charlist.push_back(Value::from_string(char.to_string()))
            }
            Value::Tuple(Rc::new(vec![
                Value::Keyword("ok"),
                Value::List(Box::new(charlist)),
            ]))
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn words(str: &Value) -> Value {
    console_log!("wordsing words");
    let str = Value::as_string(str);
    let mut words = Vector::new();
    let mut word = String::new();
    for char in str.chars() {
        if char.is_alphanumeric() || char == '\'' {
            word.push(char)
        } else if !word.is_empty() {
            words.push_back(Value::from_string(word));
            word = String::new()
        }
    }
    console_log!("words gathered into vector; returning to ludus");
    Value::list(words)
}

pub fn index_of(scrutinee: &Value, target: &Value) -> Value {
    let scrutinee = scrutinee.as_list();
    for (i, value) in scrutinee.iter().enumerate() {
        if value == target {
            return Value::from_usize(i);
        }
    }
    Value::Nil
}

pub fn indices_of(scrutinee: &Value, target: &Value) -> Value {
    let scrutinee = scrutinee.as_list();
    let mut indices = Vector::new();
    for (i, value) in scrutinee.iter().enumerate() {
        if value == target {
            indices.push_back(Value::from_usize(i))
        }
    }
    Value::list(indices)
}

// TODO: figure out how to get to opportunistic mutation here
pub fn concat(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Interned(x), Value::Interned(y)) => Value::String(Rc::new(format!("{x}{y}"))),
        (Value::String(x), Value::String(y)) => Value::String(Rc::new(format!("{x}{y}"))),
        (Value::String(x), Value::Interned(y)) => Value::String(Rc::new(format!("{x}{y}"))),
        (Value::Interned(x), Value::String(y)) => Value::String(Rc::new(format!("{x}{y}"))),
        (Value::List(x), Value::List(y)) => {
            let mut newlist = *x.clone();
            newlist.append(*y.clone());
            Value::List(Box::new(newlist))
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn append(x: &Value, y: &Value) -> Value {
    match x {
        Value::List(list) => {
            let mut newlist = list.clone();
            newlist.push_back(y.clone());
            Value::List(newlist)
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn dec(x: &Value) -> Value {
    Value::from_f64(x.as_f64() - 1.0)
}

pub fn inc(x: &Value) -> Value {
    Value::from_f64(x.as_f64() + 1.0)
}

pub fn div(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => Value::Number(x / y),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn mult(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => Value::Number(x * y),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn pow(x: &Value, y: &Value) -> Value {
    let x = x.as_f64();
    let y = y.as_f64();
    Value::from_f64(x.powf(y))
}

pub fn dissoc(dict: &Value, key: &Value) -> Value {
    match (dict, key) {
        (Value::Dict(dict), Value::Keyword(key)) => {
            let mut new = dict.clone();
            new.remove(&Key::Keyword(key));
            Value::Dict(new)
        }
        (Value::Dict(dict), Value::Interned(key)) => {
            let mut new = dict.clone();
            new.remove(&Key::Interned(key));
            Value::Dict(new)
        }
        (Value::Dict(dict), Value::String(key)) => {
            let mut new = dict.clone();
            new.remove(&Key::String(key.clone()));
            Value::Dict(new)
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn first(ordered: &Value) -> Value {
    match ordered {
        Value::List(list) => match list.front() {
            Some(n) => n.clone(),
            None => Value::Nil,
        },
        Value::Tuple(tuple) => match tuple.first() {
            Some(n) => n.clone(),
            None => Value::Nil,
        },
        Value::String(s) => match s.chars().next() {
            Some(char) => Value::from_string(char.to_string()),
            None => Value::Nil,
        },
        Value::Interned(s) => match s.chars().next() {
            Some(char) => Value::from_string(char.to_string()),
            None => Value::Nil,
        },
        _ => unreachable!("internal Ludus error"),
    }
}

// TODO: figure out how to handle negative numbers
// the cast from f64 to usize discards sign info
pub fn at(ordered: &Value, i: &Value) -> Value {
    match (ordered, i) {
        (Value::List(list), Value::Number(n)) => {
            let i = f64::from(*n) as usize;
            match list.get(i) {
                Some(n) => n.clone(),
                None => Value::Nil,
            }
        }
        (Value::Tuple(tuple), Value::Number(n)) => {
            let i = f64::from(*n) as usize;
            match tuple.get(i) {
                Some(n) => n.clone(),
                None => Value::Nil,
            }
        }
        (Value::String(s), Value::Number(n)) => {
            let i = f64::from(*n) as usize;
            match s.chars().nth(i) {
                Some(n) => Value::from_string(n.to_string()),
                None => Value::Nil,
            }
        }
        (Value::Interned(s), Value::Number(n)) => {
            let i = f64::from(*n) as usize;
            match s.chars().nth(i) {
                Some(n) => Value::from_string(n.to_string()),
                None => Value::Nil,
            }
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn get(dict: &Value, key: &Value) -> Value {
    match (dict, key) {
        (Value::Dict(dict), Value::Keyword(key)) => match dict.get(&Key::Keyword(key)) {
            Some(x) => x.clone(),
            None => Value::Nil,
        },
        (Value::Dict(dict), Value::Interned(key)) => match dict.get(&Key::Interned(key)) {
            Some(x) => x.clone(),
            None => Value::Nil,
        },
        (Value::Dict(dict), Value::String(key)) => match dict.get(&Key::String(key.clone())) {
            Some(x) => x.clone(),
            None => Value::Nil,
        },
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn last(ordered: &Value) -> Value {
    match ordered {
        Value::List(list) => match list.last() {
            Some(x) => x.clone(),
            None => Value::Nil,
        },
        Value::Tuple(tuple) => match tuple.last() {
            Some(x) => x.clone(),
            None => Value::Nil,
        },
        Value::String(s) => match s.chars().last() {
            Some(char) => Value::from_string(char.to_string()),
            None => Value::Nil,
        },
        Value::Interned(s) => match s.chars().last() {
            Some(char) => Value::from_string(char.to_string()),
            None => Value::Nil,
        },
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn print(x: &Value) -> Value {
    let Value::List(args) = x else {
        unreachable!("internal Ludus error")
    };
    let out = args
        .iter()
        .map(|val| format!("{val}"))
        .collect::<Vec<_>>()
        .join(" ");
    console_log!("{out}");
    Value::Keyword("ok")
}

pub fn show(x: &Value) -> Value {
    Value::String(Rc::new(format!("{x}")))
}

pub fn rest(ordered: &Value) -> Value {
    match ordered {
        Value::List(list) => Value::List(Box::new(list.clone().split_at(1).1)),
        Value::Tuple(tuple) => {
            Value::List(Box::new(Vector::from_iter(tuple.iter().next().cloned())))
        }
        Value::Interned(str) => Value::String(Rc::new(str.get(1..).unwrap_or("").to_string())),
        Value::String(str) => Value::String(Rc::new(
            str.clone().as_str().get(1..).unwrap_or("").to_string(),
        )),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn count(coll: &Value) -> Value {
    match coll {
        Value::Dict(d) => Value::from_usize(d.len()),
        Value::List(l) => Value::from_usize(l.len()),
        Value::Tuple(t) => Value::from_usize(t.len()),
        Value::String(s) => Value::from_usize(s.len()),
        Value::Interned(s) => Value::from_usize(s.len()),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn range(start: &Value, end: &Value) -> Value {
    match (start, end) {
        (Value::Number(start), Value::Number(end)) => {
            let start = f64::from(*start) as isize;
            let end = f64::from(*end) as isize;
            let mut range = Vector::new();
            for n in start..end {
                range.push_back(Value::from_usize(n as usize))
            }
            Value::List(Box::new(range))
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn slice(ordered: &Value, start: &Value, end: &Value) -> Value {
    match (ordered, start, end) {
        (Value::List(list), Value::Number(start), Value::Number(end)) => {
            let mut newlist = list.clone();
            let start = std::cmp::max(f64::from(*start) as usize, 0);
            let end = std::cmp::min(f64::from(*end) as usize, list.len());
            Value::List(Box::new(newlist.slice(start..end)))
        }
        // TODO: figure out something better to do than return an empty string on a bad slice
        (Value::String(string), Value::Number(start), Value::Number(end)) => {
            let start = std::cmp::max(f64::from(*start) as usize, 0);
            let end = std::cmp::min(f64::from(*end) as usize, string.len());
            Value::String(Rc::new(
                string
                    .clone()
                    .as_str()
                    .get(start..end)
                    .unwrap_or("")
                    .to_string(),
            ))
        }
        (Value::Interned(string), Value::Number(start), Value::Number(end)) => {
            let start = std::cmp::max(f64::from(*start) as usize, 0);
            let end = std::cmp::min(f64::from(*end) as usize, string.len());
            Value::String(Rc::new(string.get(start..end).unwrap_or("").to_string()))
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn list(x: &Value) -> Value {
    match x {
        Value::List(_) => x.clone(),
        Value::Tuple(t) => Value::List(Box::new(Vector::from_iter(t.iter().cloned()))),
        Value::Dict(d) => {
            let kvs = d.iter();
            let mut list = vector![];
            for (key, value) in kvs {
                let kv = Value::Tuple(Rc::new(vec![key.to_value(), value.clone()]));
                list.push_back(kv);
            }
            Value::List(Box::new(list))
        }
        _ => Value::List(Box::new(vector![x.clone()])),
    }
}

pub fn number(x: &Value) -> Value {
    match x {
        Value::Interned(string) => match string.parse::<f64>() {
            Ok(n) => Value::Tuple(Rc::new(vec![Value::Keyword("ok"), Value::from_f64(n)])),
            Err(_) => Value::Tuple(Rc::new(vec![
                Value::Keyword("err"),
                Value::String(Rc::new(format!("could not parse `{string}` as a number"))),
            ])),
        },
        Value::String(string) => match string.parse::<f64>() {
            Ok(n) => Value::Tuple(Rc::new(vec![Value::Keyword("ok"), Value::from_f64(n)])),
            Err(_) => Value::Tuple(Rc::new(vec![
                Value::Keyword("err"),
                Value::String(Rc::new(format!("could not parse `{string}` as a number"))),
            ])),
        },
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn r#type(x: &Value) -> Value {
    match x {
        Value::Nil => Value::Keyword("nil"),
        Value::Number(_) => Value::Keyword("number"),
        Value::True | Value::False => Value::Keyword("bool"),
        Value::Keyword(_) => Value::Keyword("keyword"),
        Value::Tuple(_) => Value::Keyword("tuple"),
        Value::Interned(_) => Value::Keyword("string"),
        Value::String(_) => Value::Keyword("string"),
        Value::List(_) => Value::Keyword("list"),
        Value::Dict(_) => Value::Keyword("dict"),
        Value::Fn(_) => Value::Keyword("fn"),
        Value::Box(_) => Value::Keyword("box"),
        Value::BaseFn(_) => Value::Keyword("fn"),
        Value::Partial(_) => Value::Keyword("fn"),
        Value::Process => Value::Keyword("process"),
        Value::Nothing => unreachable!(),
    }
}

pub fn split(source: &Value, splitter: &Value) -> Value {
    match (source, splitter) {
        (Value::String(source), Value::String(splitter)) => {
            println!("splitting {source} with {splitter}");
            let parts = source.split_terminator(splitter.as_str());
            let mut list = vector![];
            for part in parts {
                list.push_back(Value::String(Rc::new(part.to_string())));
            }
            Value::List(Box::new(list))
        }
        (Value::String(_), Value::Interned(splitter)) => {
            split(source, &Value::String(Rc::new(splitter.to_string())))
        }
        (Value::Interned(source), Value::String(_)) => {
            split(&Value::String(Rc::new(source.to_string())), splitter)
        }
        (Value::Interned(source), Value::Interned(splitter)) => {
            let source = Value::String(Rc::new(source.to_string()));
            let splitter = Value::String(Rc::new(splitter.to_string()));
            split(&source, &splitter)
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn upcase(string: &Value) -> Value {
    match string {
        Value::String(string) => Value::String(Rc::new(string.to_uppercase())),
        Value::Interned(string) => Value::String(Rc::new(string.to_uppercase())),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn downcase(string: &Value) -> Value {
    match string {
        Value::String(string) => Value::String(Rc::new(string.to_lowercase())),
        Value::Interned(string) => Value::String(Rc::new(string.to_lowercase())),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn trim(string: &Value) -> Value {
    match string {
        Value::String(string) => Value::String(Rc::new(string.trim().to_string())),
        Value::Interned(string) => Value::String(Rc::new(string.trim().to_string())),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn triml(string: &Value) -> Value {
    match string {
        Value::String(string) => Value::String(Rc::new(string.trim_start().to_string())),
        Value::Interned(string) => Value::String(Rc::new(string.trim_start().to_string())),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn trimr(string: &Value) -> Value {
    match string {
        Value::String(string) => Value::String(Rc::new(string.trim_end().to_string())),
        Value::Interned(string) => Value::String(Rc::new(string.trim_end().to_string())),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn atan_2(x: &Value, y: &Value) -> Value {
    let x = x.as_f64();
    let y = y.as_f64();
    Value::from_f64(x.atan2(y))
}

pub fn ceil(x: &Value) -> Value {
    Value::from_f64(x.as_f64().ceil())
}

pub fn cos(x: &Value) -> Value {
    Value::from_f64(x.as_f64().cos())
}

pub fn floor(x: &Value) -> Value {
    Value::from_f64(x.as_f64().floor())
}

pub fn base_random() -> Value {
    Value::from_f64(random())
}

pub fn round(x: &Value) -> Value {
    Value::from_f64(x.as_f64().round())
}

pub fn sin(x: &Value) -> Value {
    Value::from_f64(x.as_f64().sin())
}

pub fn sqrt(x: &Value) -> Value {
    Value::from_f64(x.as_f64().sqrt())
}

pub fn tan(x: &Value) -> Value {
    Value::from_f64(x.as_f64().tan())
}

pub fn gt(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => {
            if x > y {
                Value::True
            } else {
                Value::False
            }
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn gte(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => {
            if x >= y {
                Value::True
            } else {
                Value::False
            }
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn lt(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => {
            if x < y {
                Value::True
            } else {
                Value::False
            }
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn lte(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => {
            if x <= y {
                Value::True
            } else {
                Value::False
            }
        }
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn r#mod(x: &Value, y: &Value) -> Value {
    match (x, y) {
        (Value::Number(x), Value::Number(y)) => Value::Number(x % y),
        _ => unreachable!("internal Ludus error"),
    }
}

pub fn make_base() -> Value {
    let members = vec![
        ("add", Value::BaseFn(Box::new(BaseFn::Binary("add", add)))),
        (
            "append",
            Value::BaseFn(Box::new(BaseFn::Binary("append", append))),
        ),
        (
            "assoc",
            Value::BaseFn(Box::new(BaseFn::Ternary("assoc", assoc))),
        ),
        ("at", Value::BaseFn(Box::new(BaseFn::Binary("at", at)))),
        (
            "atan_2",
            Value::BaseFn(Box::new(BaseFn::Binary("atan_2", atan_2))),
        ),
        (
            "bool",
            Value::BaseFn(Box::new(BaseFn::Unary("bool", r#bool))),
        ),
        ("ceil", Value::BaseFn(Box::new(BaseFn::Unary("ceil", ceil)))),
        (
            "chars",
            Value::BaseFn(Box::new(BaseFn::Unary("chars", chars))),
        ),
        (
            "concat",
            Value::BaseFn(Box::new(BaseFn::Binary("concat", concat))),
        ),
        ("cos", Value::BaseFn(Box::new(BaseFn::Unary("cos", cos)))),
        (
            "count",
            Value::BaseFn(Box::new(BaseFn::Unary("count", count))),
        ),
        ("dec", Value::BaseFn(Box::new(BaseFn::Unary("dec", dec)))),
        (
            "dissoc",
            Value::BaseFn(Box::new(BaseFn::Binary("dissoc", dissoc))),
        ),
        ("div", Value::BaseFn(Box::new(BaseFn::Binary("div", div)))),
        ("doc", Value::BaseFn(Box::new(BaseFn::Unary("doc", doc)))),
        (
            "downcase",
            Value::BaseFn(Box::new(BaseFn::Unary("downcase", downcase))),
        ),
        ("eq?", Value::BaseFn(Box::new(BaseFn::Binary("eq?", eq)))),
        (
            "first",
            Value::BaseFn(Box::new(BaseFn::Unary("first", first))),
        ),
        (
            "floor",
            Value::BaseFn(Box::new(BaseFn::Unary("floor", floor))),
        ),
        ("get", Value::BaseFn(Box::new(BaseFn::Binary("get", get)))),
        ("gt?", Value::BaseFn(Box::new(BaseFn::Binary("gt?", gt)))),
        ("gte?", Value::BaseFn(Box::new(BaseFn::Binary("gte?", gte)))),
        ("inc", Value::BaseFn(Box::new(BaseFn::Unary("inc", inc)))),
        (
            "index_of",
            Value::BaseFn(Box::new(BaseFn::Binary("index_of", index_of))),
        ),
        (
            "indices_of",
            Value::BaseFn(Box::new(BaseFn::Binary("indices_of", indices_of))),
        ),
        ("last", Value::BaseFn(Box::new(BaseFn::Unary("last", last)))),
        ("list", Value::BaseFn(Box::new(BaseFn::Unary("list", list)))),
        ("lt?", Value::BaseFn(Box::new(BaseFn::Binary("lt?", lt)))),
        ("lte?", Value::BaseFn(Box::new(BaseFn::Binary("lte?", lte)))),
        ("mod", Value::BaseFn(Box::new(BaseFn::Binary("mod", r#mod)))),
        (
            "mult",
            Value::BaseFn(Box::new(BaseFn::Binary("mult", mult))),
        ),
        (
            "number",
            Value::BaseFn(Box::new(BaseFn::Unary("number", number))),
        ),
        ("pi", Value::from_f64(std::f64::consts::PI)),
        ("pow", Value::BaseFn(Box::new(BaseFn::Binary("pow", pow)))),
        (
            "print!",
            Value::BaseFn(Box::new(BaseFn::Unary("print!", print))),
        ),
        ("process", Value::Process),
        (
            "random",
            Value::BaseFn(Box::new(BaseFn::Nullary("random", base_random))),
        ),
        (
            "range",
            Value::BaseFn(Box::new(BaseFn::Binary("range", range))),
        ),
        ("rest", Value::BaseFn(Box::new(BaseFn::Unary("rest", rest)))),
        (
            "round",
            Value::BaseFn(Box::new(BaseFn::Unary("round", round))),
        ),
        ("show", Value::BaseFn(Box::new(BaseFn::Unary("show", show)))),
        ("sin", Value::BaseFn(Box::new(BaseFn::Unary("sin", sin)))),
        (
            "slice",
            Value::BaseFn(Box::new(BaseFn::Ternary("slice", slice))),
        ),
        (
            "split",
            Value::BaseFn(Box::new(BaseFn::Binary("split", split))),
        ),
        ("sqrt", Value::BaseFn(Box::new(BaseFn::Unary("sqrt", sqrt)))),
        ("sqrt_2", Value::from_f64(std::f64::consts::SQRT_2)),
        (
            "store!",
            Value::BaseFn(Box::new(BaseFn::Binary("store!", store))),
        ),
        ("sub", Value::BaseFn(Box::new(BaseFn::Binary("sub", sub)))),
        ("tan", Value::BaseFn(Box::new(BaseFn::Unary("tan", tan)))),
        ("trim", Value::BaseFn(Box::new(BaseFn::Unary("trim", trim)))),
        (
            "triml",
            Value::BaseFn(Box::new(BaseFn::Unary("triml", triml))),
        ),
        (
            "trimr",
            Value::BaseFn(Box::new(BaseFn::Unary("trimr", trimr))),
        ),
        (
            "type",
            Value::BaseFn(Box::new(BaseFn::Unary("type", r#type))),
        ),
        (
            "unbox",
            Value::BaseFn(Box::new(BaseFn::Unary("unbox", unbox))),
        ),
        (
            "upcase",
            Value::BaseFn(Box::new(BaseFn::Unary("upcase", upcase))),
        ),
        (
            "words",
            Value::BaseFn(Box::new(BaseFn::Unary("words", words))),
        ),
    ];
    let members = members
        .iter()
        .map(|(name, bfn)| (Key::Keyword(name), bfn.clone()))
        .collect::<Vec<_>>();
    Value::Dict(Box::new(HashMap::from(members)))
}
