diff options
| author | Daniel Csillag <dccsillag@gmail.com> | 2023-04-11 07:48:17 -0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-04-11 12:48:17 +0200 |
| commit | a8087a9dbb8b24b451bfaa5d31e07e9b5574226d (patch) | |
| tree | a726cd4d80c82b9ae40c6e2fa69fca326ffbd9ea /src/eval | |
| parent | f58ed110da56f4e2fc2d0b8c390c42359cc0f43c (diff) | |
Array sorting by key (#584)
Diffstat (limited to 'src/eval')
| -rw-r--r-- | src/eval/array.rs | 47 | ||||
| -rw-r--r-- | src/eval/methods.rs | 2 |
2 files changed, 36 insertions, 13 deletions
diff --git a/src/eval/array.rs b/src/eval/array.rs index 394191ea..6bd2eb47 100644 --- a/src/eval/array.rs +++ b/src/eval/array.rs @@ -6,6 +6,7 @@ use ecow::{eco_format, EcoString, EcoVec}; use super::{ops, Args, Func, Value, Vm}; use crate::diag::{At, SourceResult, StrResult}; +use crate::syntax::Span; use crate::util::pretty_array_like; /// Create a new [`Array`] from values. @@ -276,23 +277,45 @@ impl Array { Ok(result) } - /// Return a sorted version of this array. + /// Return a sorted version of this array, optionally by a given key function. /// - /// Returns an error if two values could not be compared. - pub fn sorted(&self) -> StrResult<Self> { + /// Returns an error if two values could not be compared or if the key function (if given) + /// yields an error. + pub fn sorted( + &self, + vm: &mut Vm, + span: Span, + key: Option<Func>, + ) -> SourceResult<Self> { let mut result = Ok(()); let mut vec = self.0.clone(); + let mut key_of = |x: Value| match &key { + // NOTE: We are relying on `comemo`'s memoization of function + // evaluation to not excessively reevaluate the `key`. + Some(f) => f.call_vm(vm, Args::new(f.span(), [x])), + None => Ok(x), + }; vec.make_mut().sort_by(|a, b| { - a.partial_cmp(b).unwrap_or_else(|| { - if result.is_ok() { - result = Err(eco_format!( - "cannot order {} and {}", - a.type_name(), - b.type_name(), - )); + // Until we get `try` blocks :) + match (key_of(a.clone()), key_of(b.clone())) { + (Ok(a), Ok(b)) => a.partial_cmp(&b).unwrap_or_else(|| { + if result.is_ok() { + result = Err(eco_format!( + "cannot order {} and {}", + a.type_name(), + b.type_name(), + )) + .at(span); + } + Ordering::Equal + }), + (Err(e), _) | (_, Err(e)) => { + if result.is_ok() { + result = Err(e); + } + Ordering::Equal } - Ordering::Equal - }) + } }); result.map(|_| Self::from_vec(vec)) } diff --git a/src/eval/methods.rs b/src/eval/methods.rs index 8b364fcb..452b90da 100644 --- a/src/eval/methods.rs +++ b/src/eval/methods.rs @@ -115,7 +115,7 @@ pub fn call( let last = args.named("last")?; array.join(sep, last).at(span)? } - "sorted" => Value::Array(array.sorted().at(span)?), + "sorted" => Value::Array(array.sorted(vm, span, args.named("key")?)?), "enumerate" => Value::Array(array.enumerate()), _ => return missing(), }, |
