Idea for a possibly better Collection occurrencesOf method.
Ramon Leon
ramon.leon at allresnet.com
Tue Sep 12 00:34:11 UTC 2006
> Is there any reason why it shouldn't look more like this:
>
> Collection >> occurrencesOf: anObject
> "Answer how many of the receiver's elements are equal
> to anObject."
>
> ^self inject: 0 into: [:tally :each |
> anObject = each
> ifTrue: [tally _ tally + 1]
> ifFalse: [tally]]
>
>
> Regards,
>
> Ray
Or..
Collection >> occurrencesOf: anObject
"Answer how many of the receiver's elements are equal to anObject."
^self inject: 0 into: [:tally :each |
anObject = each ifTrue: [tally + 1] ifFalse: [tally]]
No need to add modify tally, simply return it + 1. There's lot's of old
code in the image, without a comment, it's impossible to know why
occurrencesOf: or count: wasn't used, maybe the author just didn't know
about them. I wasn't aware of count: myself, but it should be implemented
with inject:into: as well, I'd imagine. Though implementing with count:
does seem the simplest solution.
More information about the Squeak-dev
mailing list
|