added sort and median helper functions

This commit is contained in:
Valerie Wolfe 2024-11-12 15:02:37 -05:00
parent eba5317419
commit c50f0a06e7
2 changed files with 26 additions and 2 deletions

View file

@ -158,11 +158,33 @@ pub fn average(arg: &Value) -> EvalResult {
total += total +=
if let Value::Float(float) = arg { float.clone() } if let Value::Float(float) = arg { float.clone() }
else if let Value::Int(int) = arg { int.clone() as f64 } else if let Value::Int(int) = arg { int.clone() as f64 }
else { todo!() }; else { return Err(EvalexprError::expected_number(arg.clone())) };
} }
Ok( (total / len).into() ) Ok( (total / len).into() )
} else { todo!() } } else { Err(EvalexprError::expected_tuple(arg.clone())) }
}
pub fn median(arg: &Value) -> EvalResult {
if arg.is_tuple() {
let args = sort(arg).unwrap().as_tuple().unwrap();
let len = args.len();
let middle = len / 2;
if len % 2 != 0 { Ok(args[middle].as_number().unwrap().into()) }
else {
let left = args[middle - 1].as_number().unwrap();
let right = args[middle].as_number().unwrap();
Ok( ((left + right) / 2f64 ).into() )
}
} else { Err(EvalexprError::expected_tuple(arg.clone())) }
}
pub fn sort(arg: &Value) -> EvalResult {
if let Value::Tuple(args) = arg {
let mut args = args.clone();
args.sort_by(|a, b| a.as_number().unwrap().total_cmp(&b.as_number().unwrap()));
Ok(args.into())
} else { Err(EvalexprError::expected_tuple(arg.clone())) }
} }
// Radix conversion // Radix conversion

View file

@ -38,6 +38,8 @@ pub fn build(args: &mut Arguments) -> HashMapContext {
// data science functions // data science functions
"avg" => Function::new(|arg| helper::average(arg)), "avg" => Function::new(|arg| helper::average(arg)),
"med" => Function::new(|arg| helper::median(arg)),
"sort" => Function::new(|arg| helper::sort(arg)),
// radix functions // radix functions
"bin" => Function::new(|arg| helper::binary(arg)), "bin" => Function::new(|arg| helper::binary(arg)),