Skip to content

Commit

Permalink
Merge pull request #386 from CAIMEOX/map_inplace
Browse files Browse the repository at this point in the history
Map inplace implementation
  • Loading branch information
bobzhang committed May 13, 2024
2 parents eb0a293 + 66423e6 commit 24bf4ae
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
26 changes: 26 additions & 0 deletions vec/vec.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,19 @@ pub fn map[T, U](self : Vec[T], f : (T) -> U) -> Vec[U] {
Vec::{ buf, len: self.length() }
}

/// Maps a function over the elements of the vector in place.
///
/// # Example
/// ```
/// let v = Vec::from_array([3, 4, 5])
/// v.map_inplace(fn (x) {x + 1})
/// ```
pub fn map_inplace[T](self : Vec[T], f : (T) -> T) -> Unit {
for i = 0; i < self.length(); i = i + 1 {
self[i] = f(self[i])
}
}

/// Maps a function over the elements of the vector with index.
///
/// # Example
Expand All @@ -368,6 +381,19 @@ pub fn mapi[T, U](self : Vec[T], f : (Int, T) -> U) -> Vec[U] {
Vec::{ buf, len: self.length() }
}

/// Maps a function over the elements of the vector with index in place.
///
/// # Example
/// ```
/// let v = Vec::from_array([3, 4, 5])
/// v.mapi_inplace(fn (i, x) {x + i})
/// ```
pub fn mapi_inplace[T](self : Vec[T], f : (Int, T) -> T) -> Unit {
for i = 0; i < self.length(); i = i + 1 {
self[i] = f(i, self[i])
}
}

/// Test if the vector is empty.
///
/// # Example
Expand Down
2 changes: 2 additions & 0 deletions vec/vec.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ impl Vec {
join[T](Self[Self[T]], T) -> Self[T]
length[T](Self[T]) -> Int
map[T, U](Self[T], (T) -> U) -> Self[U]
map_inplace[T](Self[T], (T) -> T) -> Unit
mapi[T, U](Self[T], (Int, T) -> U) -> Self[U]
mapi_inplace[T](Self[T], (Int, T) -> T) -> Unit
new[T]() -> Self[T]
op_add[T](Self[T], Self[T]) -> Self[T]
op_as_view[T](Self[T], ~start : Int, ~end : Int) -> VecView[T]
Expand Down
18 changes: 18 additions & 0 deletions vec/vec_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ test "map" {
inspect(Vec::["a", "b", "c"], content="Vec::[a, b, c]")?
}

test "map_inplace" {
let v = Vec::[3, 4, 5]
let e : Vec[Int] = Vec::[]
v.map_inplace(fn(x) { x + 1 })
e.map_inplace(fn(x) { x + 1 })
inspect(v, content="Vec::[4, 5, 6]")?
inspect(e, content="Vec::[]")?
}

test "mapi" {
let v = Vec::[3, 4, 5]
let e : Vec[Int] = Vec::[]
Expand All @@ -165,6 +174,15 @@ test "mapi" {
inspect(e.mapi(fn(_i, x) { x + 1 }), content="Vec::[]")?
}

test "mapi_inplace" {
let v = Vec::[3, 4, 5]
let e : Vec[Int] = Vec::[]
v.mapi_inplace(fn(i, x) { x + i })
e.mapi_inplace(fn(_i, x) { x + 1 })
inspect(v, content="Vec::[3, 5, 7]")?
inspect(e, content="Vec::[]")?
}

test "is_empty" {
let v = Vec::new()
@assertion.assert_true(v.is_empty())?
Expand Down

0 comments on commit 24bf4ae

Please sign in to comment.