mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[stdlib] Add `count(List, value)` method

Open JoeLoser opened this issue 10 months ago • 8 comments

Similar to Python's list.count(x) method, we should have the same for our List. It can't be a member method yet due to lack of conditional conformance in requiring the __eq__ trait (it's not present in CollectionElement today).

As I suggest in https://github.com/modularml/mojo/pull/2190#issuecomment-2062101102, we could add this as a free function since we don't have conditional conformance e.g.

trait ComparableCollectionElement(EqualityComparable, CollectionElement):
    pass

def count[T: ComparableCollectionElement](arg: List[T], value: T):
   ...

in list.mojo.

JoeLoser avatar Apr 11 '24 22:04 JoeLoser

I think this would require adding EqualityComparable to CollectionElement, and/or conditional conformance, right?

arthurevans avatar Apr 11 '24 22:04 arthurevans

I think this would require adding EqualityComparable to CollectionElement, and/or conditional conformance, right?

Ah, yes. I removed the "good first issue" as we can't do this yet. Thanks.

JoeLoser avatar Apr 11 '24 22:04 JoeLoser

Can you provide some code reference?

whym1here avatar Apr 12 '24 15:04 whym1here

As I suggest in https://github.com/modularml/mojo/pull/2190#issuecomment-2062101102, we could add this as a free function since we don't have conditional conformance e.g.

def count[T: CollectionElement](arg: List[T], value: T):
   ...

in list.mojo. So, marking this back as "good first issue" since it can be implemented today.

JoeLoser avatar Apr 17 '24 23:04 JoeLoser

Can you provide some code reference?

Of course. This is referring to the List.count(x) method in Python - see the docs.

Example code in Python

xs = [42, 100, 100]
xs.count(42) # 1
xs.count(100) # 2
xs.count(23) # 0

JoeLoser avatar Apr 17 '24 23:04 JoeLoser

Can you assign this to me @JoeLoser

StandinKP avatar Apr 18 '24 00:04 StandinKP

Can you assign this to me @JoeLoser

Done!

JoeLoser avatar Apr 18 '24 00:04 JoeLoser

@JoeLoser Should I wait for #2190 to be merged before taking this up again? Also a small doubt: The value for each of the element is a mlir type right? How do we compare the mlir type with value?

StandinKP avatar Apr 23 '24 14:04 StandinKP