Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[mojo-stdlib] Add List.count(value) method #2406

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 27 additions & 1 deletion stdlib/src/collections/list.mojo
Expand Up @@ -20,7 +20,6 @@ from collections import List
"""


from builtin.value import StringableCollectionElement
from memory import UnsafePointer, Reference
from memory.unsafe_pointer import move_pointee, move_from_pointee
from .optional import Optional
Expand Down Expand Up @@ -666,3 +665,30 @@ struct List[T: CollectionElement](CollectionElement, Sized, Boolable):
result += ", "
result += "]"
return result

@staticmethod
fn count[T: ComparableCollectionElement](self: List[T], value: T) -> Int:
"""Counts the number of occurrences of a value in the list.
StandinKP marked this conversation as resolved.
Show resolved Hide resolved
Note that since we can't condition methods on a trait yet,
the way to call this method is a bit special. Here is an example below.

```mojo
var my_list = List[Int](1, 2, 3)
print(__type_of(my_list).count(my_list, 1))
```

When the compiler supports conditional methods, then a simple `my_list.count(1)` will
be enough.

Args:
self: The list to search.
value: The value to count.

Returns:
The number of occurrences of the value in the list.
"""
var count = 0
for i in range(len(self)):
if self[i] == value:
count += 1
return count
11 changes: 11 additions & 0 deletions stdlib/test/collections/test_list.mojo
Expand Up @@ -682,6 +682,16 @@ def test_converting_list_to_string():
assert_equal(__type_of(my_list3).__str__(my_list3), "[1.0, 2.0, 3.0]")


def test_list_count():
JoeLoser marked this conversation as resolved.
Show resolved Hide resolved
var list = List[Int](1, 2, 3, 2, 5, 6, 7, 8, 9, 10)
assert_equal(1, __type_of(list).count(list, 1))
assert_equal(2, __type_of(list).count(list, 2))
assert_equal(0, __type_of(list).count(list, 4))

var list2 = List[Int]()
assert_equal(0, __type_of(list2).count(list2, 1))


def main():
test_mojo_issue_698()
test_list()
Expand All @@ -706,3 +716,4 @@ def main():
test_constructor_from_pointer()
test_constructor_from_other_list_through_pointer()
test_converting_list_to_string()
test_list_count()