Skip to content

Commit

Permalink
add Array::rev_iter (#1455)
Browse files Browse the repository at this point in the history
  • Loading branch information
bobzhang authored Jan 9, 2025
1 parent 1a440a7 commit 604ace1
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
32 changes: 32 additions & 0 deletions builtin/array.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions immut/list/list.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down

0 comments on commit 604ace1

Please sign in to comment.