Skip to content

Commit 786e580

Browse files
committed
[stdlib] Add List.map(fn(mut T)->None)
Signed-off-by: rd4com <[email protected]>
1 parent ec3dad7 commit 786e580

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

stdlib/src/collections/list.mojo

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,35 @@ struct List[T: CollectionElement, hint_trivial_type: Bool = False](
930930
"""
931931
return self.data
932932

933+
fn map(ref self, func: fn (mut T) -> None) -> Self:
934+
"""Map the values of the list into a new list trough a function.
935+
936+
Args:
937+
func: The function used on every elements to create the new list.
938+
939+
Returns:
940+
A new `List` created by calling `func` on every elements of `self`.
941+
942+
For example:
943+
```mojo
944+
fn MyFunc(mut e: Int):
945+
e+=1
946+
947+
var MyList = List(0, 1, 2).map(MyFunc)
948+
949+
print(
950+
MyList[0] == 1,
951+
MyList[1] == 2,
952+
MyList[2] == 3,
953+
)
954+
```.
955+
956+
"""
957+
var tmp = self
958+
for i in tmp:
959+
func(i[])
960+
return tmp
961+
933962
934963
fn _clip(value: Int, start: Int, end: Int) -> Int:
935964
return max(start, min(value, end))

stdlib/test/collections/test_list.mojo

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,21 @@ def test_list_repr():
924924
assert_equal(empty.__repr__(), "[]")
925925

926926

927+
def test_list_map():
928+
fn MyFunc(mut e: Int):
929+
e += 1
930+
931+
var lst = List(0, 1, 2).map(MyFunc)
932+
for e in range(len(lst)):
933+
assert_equal(lst[e], e + 1)
934+
935+
lst = List(0, 1, 2)
936+
var lst2 = lst.map(MyFunc)
937+
for e in range(len(lst)):
938+
assert_equal(lst[e], e)
939+
assert_equal(lst2[e], e + 1)
940+
941+
927942
# ===-------------------------------------------------------------------===#
928943
# main
929944
# ===-------------------------------------------------------------------===#
@@ -962,3 +977,4 @@ def main():
962977
test_indexing()
963978
test_list_dtor()
964979
test_list_repr()
980+
test_list_map()

0 commit comments

Comments
 (0)