Skip to main content

rl_lang/interpreter/stdlib/array/
arr_sort.rs

1use crate::{
2    ast::statements::TypeAnnotation,
3    interpreter::{evaluator::Evaluator, values::Value},
4    utils::{errors::Error, span::Span},
5};
6
7pub fn std_arr_sort(eval: &mut Evaluator, array: Value, span: Span) -> Result<Value, Error> {
8    match array {
9        Value::Values {
10            items_type,
11            mut items,
12        } => match items_type {
13            TypeAnnotation::Int => {
14                items.sort_by(|a, b| {
15                    if let (Value::Integer(x), Value::Integer(y)) = (a, b) {
16                        x.cmp(y)
17                    } else {
18                        std::cmp::Ordering::Equal
19                    }
20                });
21                Ok(Value::Values { items_type, items })
22            }
23            TypeAnnotation::Float => {
24                items.sort_by(|a, b| {
25                    if let (Value::Float(x), Value::Float(y)) = (a, b) {
26                        x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
27                    } else {
28                        std::cmp::Ordering::Equal
29                    }
30                });
31                Ok(Value::Values { items_type, items })
32            }
33            _ => Err(eval.err(
34                "arr_sort() accepts only int or float arrays".to_string(),
35                span,
36            )),
37        },
38        _ => Err(eval.err("arr_sort() accepts only arrays".to_string(), span)),
39    }
40}