Idea for a possibly better Collection occurrencesOf method.

Raymond W. Lucke IV smalltalk at raylucke.com
Mon Sep 11 23:42:10 UTC 2006


Hello,

I am new to the Squeak community, and new to Smalltalk itself. I have  
been going through the browser looking at how things work and  
stumbled upon the occurrences of method of Collection:

Collection >> occurrencesOf: anObject
	"Answer how many of the receiver's elements are equal to anObject."

	| tally |
	tally _ 0.
	self do: [:each | anObject = each ifTrue: [tally _ tally + 1]].
	^tally

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]]


It seems to me that not using inject there might be reinventing the  
wheel. Please excuse my ignorance if I'm incorrect here, I'm trying  
to learn Smalltalk and get involved. Any ideas?

Regards,

Ray



More information about the Squeak-dev mailing list