Skip to content

Commit

Permalink
Add List.map(fn(mut T)->None)
Browse files Browse the repository at this point in the history
Signed-off-by: rd4com <[email protected]>
  • Loading branch information
rd4com committed Dec 5, 2024
1 parent ec3dad7 commit 9d20a4a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
29 changes: 29 additions & 0 deletions stdlib/src/collections/list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,35 @@ struct List[T: CollectionElement, hint_trivial_type: Bool = False](
"""
return self.data

fn map(ref self, func: fn (mut T) -> None) -> Self:
"""Map the values of the list into a new list trough a function.
Args:
func: The function used on every elements to create the new list.
Returns:
A new `List` created by calling `func` on every elements of `self`.
For example:
```mojo
fn MyFunc(mut e: Int):
e+=1
var MyList = List(0, 1, 2).map(MyFunc)
print(
MyList[0] == 1,
MyList[1] == 2,
MyList[2] == 3,
)
```.
"""
var tmp = self
for i in tmp:
func(i[])
return tmp
fn _clip(value: Int, start: Int, end: Int) -> Int:
return max(start, min(value, end))
Expand Down
16 changes: 16 additions & 0 deletions stdlib/test/collections/test_list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,21 @@ def test_list_repr():
assert_equal(empty.__repr__(), "[]")


def test_list_map():
fn MyFunc(mut e: Int):
e += 1

var lst = List(0, 1, 2).map(MyFunc)
for e in range(len(lst)):
assert_equal(lst[e], e + 1)

lst = List(0, 1, 2)
var lst2 = lst.map(MyFunc)
for e in range(len(lst)):
assert_equal(lst[e], e)
assert_equal(lst2[e], e + 1)


# ===-------------------------------------------------------------------===#
# main
# ===-------------------------------------------------------------------===#
Expand Down Expand Up @@ -962,3 +977,4 @@ def main():
test_indexing()
test_list_dtor()
test_list_repr()
test_list_map()

0 comments on commit 9d20a4a

Please sign in to comment.