Skip to content

Commit

Permalink
[stdlib] Add ListLiteral.__getitem__
Browse files Browse the repository at this point in the history
Signed-off-by: rd4com <[email protected]>
  • Loading branch information
rd4com committed Dec 4, 2024
1 parent ec3dad7 commit ecc5490
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
27 changes: 27 additions & 0 deletions stdlib/src/builtin/builtin_list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,33 @@ struct ListLiteral[*Ts: CollectionElement](Sized, CollectionElement):
"""
return value in self.storage

@always_inline
fn __getitem__[
i: Int
](ref self) -> ref [self.storage] __type_of(self.storage).element_types[
i.value
]:
"""Get a list element at the given index.
Parameters:
i: The element index.
Returns:
The element at the given index.
For example:
```mojo
def main():
x = [0, 1.0, "two"]
print(
x[0] == 0,
x[1] == 1.0,
x[2] == "two"
)
```.
"""
return self.storage[i]
# ===-----------------------------------------------------------------------===#
# VariadicList / VariadicListMem
Expand Down
21 changes: 20 additions & 1 deletion stdlib/test/builtin/test_list_literal.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
# ===----------------------------------------------------------------------=== #
# RUN: %mojo %s

from testing import assert_equal, assert_false, assert_true
from testing import assert_equal, assert_false, assert_true, assert_not_equal
from sys.intrinsics import _type_is_eq


def test_list():
Expand Down Expand Up @@ -66,7 +67,25 @@ def test_contains():
assert_true("Mojo" not in h and String("Mojo") in h)


def test_list_literal_dunder_getitem():
x = [0, True, 1.0, "two"]
assert_equal(x[0], 0)
assert_not_equal(x[0], 1)
assert_equal(x[1], True)
assert_not_equal(x[1], False)
assert_equal(x[2], 1.0)
assert_not_equal(x[2], 1.5)
assert_equal(x[3], "two")
assert_not_equal(x[3], "abc")

assert_true(_type_is_eq[__type_of(x[0]), Int]())
assert_true(_type_is_eq[__type_of(x[1]), Bool]())
assert_true(_type_is_eq[__type_of(x[2]), Float64]())
assert_true(_type_is_eq[__type_of(x[3]), StringLiteral]())


def main():
test_list()
test_variadic_list()
test_contains()
test_list_literal_dunder_getitem()

0 comments on commit ecc5490

Please sign in to comment.