feat: count function for collections

This commit is contained in:
Roman Godmaire 2024-05-04 17:26:26 -04:00
parent 59dfe1e854
commit a612bb771b
2 changed files with 19 additions and 0 deletions

13
src/env/core.rs vendored
View file

@ -142,6 +142,19 @@ pub(super) fn core() -> HashMap<String, Node> {
} }
}), }),
), ),
(
"count",
Node::NativeFunc(|_env, args| {
arg_count!(1, args.len());
match args[0].borrow() {
Node::List(list) => Ok(Node::Int(list.len() as i64)),
Node::Vector(vec) => Ok(Node::Int(vec.len() as i64)),
Node::Map(map) => Ok(Node::Int(map.len() as i64)),
_ => Err(Error::ExpectedCollection)?,
}
}),
),
// Ordering // Ordering
( (
"eq?", "eq?",

View file

@ -114,18 +114,24 @@ mod test {
#[case("(list? 23)", "false")] #[case("(list? 23)", "false")]
#[case("(empty? (list 1 2 3))", "false")] #[case("(empty? (list 1 2 3))", "false")]
#[case("(empty? (list))", "true")] #[case("(empty? (list))", "true")]
#[case("(count (list))", "0")]
#[case("(count (list 1 2 3))", "3")]
// Vectors // Vectors
#[case("(vector 1 2 3)", "[1 2 3]")] #[case("(vector 1 2 3)", "[1 2 3]")]
#[case("(vector? [])", "true")] #[case("(vector? [])", "true")]
#[case("(vector? 23)", "false")] #[case("(vector? 23)", "false")]
#[case("(empty? [1 2 3])", "false")] #[case("(empty? [1 2 3])", "false")]
#[case("(empty? [])", "true")] #[case("(empty? [])", "true")]
#[case("(count [])", "0")]
#[case("(count [1 2 3])", "3")]
// Hashmaps // Hashmaps
#[case("(hashmap :a 1)", "{:a: 1}")] #[case("(hashmap :a 1)", "{:a: 1}")]
#[case("(hashmap? {})", "true")] #[case("(hashmap? {})", "true")]
#[case("(hashmap? 23)", "false")] #[case("(hashmap? 23)", "false")]
#[case("(empty? {:a 1})", "false")] #[case("(empty? {:a 1})", "false")]
#[case("(empty? {})", "true")] #[case("(empty? {})", "true")]
#[case("(count {})", "0")]
#[case("(count {:a 1})", "1")]
// Environment manipulation // Environment manipulation
#[case("(define! asdf (+ 2 2)) (+ asdf 2)", "4\n6")] #[case("(define! asdf (+ 2 2)) (+ asdf 2)", "4\n6")]
#[case("(let* (a 2) (+ a 2))", "4")] #[case("(let* (a 2) (+ a 2))", "4")]