diff --git a/builtin/array.mbt b/builtin/array.mbt index af3bceb3d..45bb62ae6 100644 --- a/builtin/array.mbt +++ b/builtin/array.mbt @@ -1661,6 +1661,38 @@ pub fn iter[T](self : Array[T]) -> Iter[T] { }) } +///| +/// Returns an iterator that yields elements from the array in reverse order, +/// from the last element to the first. +/// +/// Parameters: +/// +/// * `array` : The array to iterate over in reverse order. +/// +/// Returns an iterator that yields each element of the array, starting from the +/// last element and moving towards the first. +/// +/// Example: +/// +/// ```moonbit +/// test "Array::rev_iter" { +/// let arr = [1, 2, 3] +/// let result = [] +/// arr.rev_iter().each(fn(x) { result.push(x) }) +/// inspect!(result, content="[3, 2, 1]") +/// } +/// ``` +pub fn rev_iter[T](self : Array[T]) -> Iter[T] { + Iter::new(fn(yield_) { + for i = self.length() - 1; i >= 0; i = i - 1 { + guard let IterContinue = yield_(self.unsafe_get(i)) else { x => break x } + + } else { + IterContinue + } + }) +} + ///| /// Returns an iterator that provides both indices and values of the array in /// order. diff --git a/builtin/builtin.mbti b/builtin/builtin.mbti index 65dd2aabd..fb1231f23 100644 --- a/builtin/builtin.mbti +++ b/builtin/builtin.mbti @@ -107,6 +107,7 @@ impl Array { rev_fold[A, B](Self[A], init~ : B, (B, A) -> B) -> B rev_foldi[A, B](Self[A], init~ : B, (Int, B, A) -> B) -> B rev_inplace[T](Self[T]) -> Unit + rev_iter[T](Self[T]) -> Iter[T] search[T : Eq](Self[T], T) -> Int? search_by[T](Self[T], (T) -> Bool) -> Int? shrink_to_fit[T](Self[T]) -> Unit diff --git a/immut/list/list.mbt b/immut/list/list.mbt index 5677cc525..df436a3f9 100644 --- a/immut/list/list.mbt +++ b/immut/list/list.mbt @@ -30,9 +30,11 @@ pub fn T::to_string[A : Show](xs : T[A]) -> String { ///| pub impl[A : ToJson] ToJson for T[A] with to_json(self) { let capacity = self.length() - guard capacity != 0 else { return Array([]) } + guard capacity != 0 else { return [] } let jsons = Array::new(capacity~) - self.each(fn(a) { jsons.push(a.to_json()) }) + for a in self { + jsons.push(a.to_json()) + } Array(jsons) }