cl-interpret/builtin: Add len builtin as a quick hack to write more interesting programs.

This is temporary, I just want a way to get the length of a thing atm.
This commit is contained in:
John 2024-07-27 18:43:03 -05:00
parent a233bb18bc
commit b2733aa171

View File

@ -10,6 +10,7 @@ use cl_ast::Sym;
use std::{ use std::{
io::{stdout, Write}, io::{stdout, Write},
rc::Rc, rc::Rc,
slice,
}; };
builtins! { builtins! {
@ -57,6 +58,19 @@ builtins! {
println!("{}", *env); println!("{}", *env);
Ok(ConValue::Empty) Ok(ConValue::Empty)
} }
pub fn len<env, _>(list) -> IResult<ConValue> {
Ok(ConValue::Int(match list {
ConValue::Empty => 0,
ConValue::String(s) => s.chars().count() as _,
ConValue::Ref(r) => return len.call(env, slice::from_ref(r.as_ref())),
ConValue::Array(t) => t.len() as _,
ConValue::Tuple(t) => t.len() as _,
ConValue::RangeExc(start, end) => (end - start) as _,
ConValue::RangeInc(start, end) => (end - start + 1) as _,
_ => Err(Error::TypeError)?,
}))
}
} }
builtins! { builtins! {
const BINARY; const BINARY;