Skip to content

Commit 8efd1db

Browse files
feat(iter): add mapi (#2011)
1 parent 894a0e9 commit 8efd1db

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

builtin/builtin.mbti

+1
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ impl Iter {
243243
#deprecated
244244
map_option[A, B](Self[A], (A) -> B?) -> Self[B]
245245
map_while[A, B](Self[A], (A) -> B?) -> Self[B]
246+
mapi[T, R](Self[T], (Int, T) -> R) -> Self[R]
246247
maximum[T : Compare](Self[T]) -> T?
247248
minimum[T : Compare](Self[T]) -> T?
248249
new[T](((T) -> IterResult) -> IterResult) -> Self[T]

builtin/iter.mbt

+30
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,36 @@ pub fn Iter::map[T, R](self : Iter[T], f : (T) -> R) -> Iter[R] {
415415
fn { yield_ => self.run(fn { a => yield_(f(a)) }) }
416416
}
417417

418+
///|
419+
/// Transforms the elements of the iterator using a mapping function.
420+
///
421+
/// # Type Parameters
422+
///
423+
/// - `T`: The type of the elements in the iterator.
424+
/// - `R`: The type of the transformed elements.
425+
///
426+
/// # Arguments
427+
///
428+
/// * `self` - The input iterator.
429+
/// * `f` - The mapping function that transforms each element of the iterator with index.
430+
///
431+
/// # Returns
432+
///
433+
/// A new iterator that contains the transformed elements.
434+
pub fn Iter::mapi[T, R](self : Iter[T], f : (Int, T) -> R) -> Iter[R] {
435+
fn {
436+
yield_ => {
437+
let mut i = -1
438+
self.run(fn {
439+
a => {
440+
i = i + 1
441+
yield_(f(i, a))
442+
}
443+
})
444+
}
445+
}
446+
}
447+
418448
///|
419449
/// Transforms the elements of the iterator using a mapping function that returns an `Option`.
420450
/// The elements for which the function returns `None` are filtered out.

builtin/iter_test.mbt

+10
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,16 @@ test "map" {
236236
inspect!(exb, content="23456")
237237
}
238238

239+
///|
240+
test "mapi" {
241+
let iter = test_from_array(['1', '2', '3', '4', '5'])
242+
let exb = StringBuilder::new(size_hint=0)
243+
iter
244+
.mapi(fn { i, x => (i + x.to_int()).to_char().unwrap() })
245+
.each(fn { x => exb.write_char(x) })
246+
inspect!(exb, content="13579")
247+
}
248+
239249
///|
240250
test "filter_map" {
241251
let arr = [1, 2, 3, 4, 5]

0 commit comments

Comments
 (0)