From 3481d8cc81a2b3a14118869c7f0ffe204ff3efc8 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 31 Aug 2021 12:59:53 +0200 Subject: More utility functions - join("a", "b", "c", sep: ", ") - int("12") - float("31.4e-1") - str(10) - sorted((3, 2, 1)) --- src/eval/array.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src/eval/array.rs') diff --git a/src/eval/array.rs b/src/eval/array.rs index acf44ab2..bae89c4b 100644 --- a/src/eval/array.rs +++ b/src/eval/array.rs @@ -1,3 +1,4 @@ +use std::cmp::Ordering; use std::convert::TryFrom; use std::fmt::{self, Debug, Display, Formatter, Write}; use std::iter::FromIterator; @@ -80,6 +81,26 @@ impl Array { self.0.iter() } + /// Return a sorted version of this array. + /// + /// Returns an error if two values could not be compared. + pub fn sorted(mut self) -> StrResult { + let mut result = Ok(()); + Rc::make_mut(&mut self.0).sort_by(|a, b| { + a.partial_cmp(b).unwrap_or_else(|| { + if result.is_ok() { + result = Err(format!( + "cannot compare {} with {}", + a.type_name(), + b.type_name(), + )); + } + Ordering::Equal + }) + }); + result.map(|_| self) + } + /// Repeat this array `n` times. pub fn repeat(&self, n: i64) -> StrResult { let count = usize::try_from(n) -- cgit v1.2.3