Skip to content

Commit

Permalink
[External] [mojo-stdlib] Add List.count(value) method (#38915)
Browse files Browse the repository at this point in the history
[External] [mojo-stdlib] Add `List.count(value)` method

Add `List.count(value)` method to count the number of occurrences of a
value in the `List`.

Fixes #2263

---------

Co-authored-by: Kaushal Phulgirkar <kaushalpp01@gmail.com>
Closes #2406
MODULAR_ORIG_COMMIT_REV_ID: e9e9be6db11d56f951e94daf22fd0ff8520615fa
  • Loading branch information
StandinKP authored and JoeLoser committed May 3, 2024
1 parent 802bb8d commit c37a3ec
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
32 changes: 31 additions & 1 deletion stdlib/src/collections/list.mojo
Original file line number Diff line number Diff line change
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 @@ -658,3 +657,34 @@ 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.
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.
Parameters:
T: The type of the elements in the list. Must implement the
traits `EqualityComparable` and `CollectionElement`.
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 elem in self:
if elem[] == value:
count += 1
return count
11 changes: 11 additions & 0 deletions stdlib/test/collections/test_list.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,16 @@ def test_converting_list_to_string():
)


def test_list_count():
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 @@ -703,3 +713,4 @@ def main():
test_constructor_from_pointer()
test_constructor_from_other_list_through_pointer()
test_converting_list_to_string()
test_list_count()

0 comments on commit c37a3ec

Please sign in to comment.