[ENH][CCP] CCP002-OCAtIfAbsentPut

Marcus Denker marcus at ira.uka.de
Wed Nov 19 18:07:10 UTC 2003


Am 16.11.2003 um 23:30 schrieb ducasse:

> Hi marcus
>
> I just wanted to know
>
> why don't you define it as:
> at: anIndex ifAbsentPut: aBlock
> 	^self at: anIndex ifAbsent: [self at: anIndex put: aBlock value]
>
Because "at:put:" does not grow a collection, it simply raises
an Error if the index is larger than the size of the Collection...
  Here's a test:

testAtIfAbsentPut
	| col |
	col := OrderedCollection new.
	
	self shouldnt: [col at: 5 ifAbsentPut: 'hallo'] raise: Error.
	self assert: (col size = 5).
	self assert: (col at: 5) = 'hallo'.


This fails with your code, because at:put in Squeak's OrderedCollection
is defined as

at: anInteger put: anObject
	"Put anObject at element index anInteger. at:put: cannot be used to
	append, front or back, to an ordered collection; it is used by a
	knowledgeable client to replace an element."

	| index |
	index _ anInteger asInteger.
	(index < 1 or: [index + firstIndex - 1 > lastIndex])
		ifTrue: [self errorNoSuchElement]
		ifFalse: [^array at: index + firstIndex - 1 put: anObject]


--
Marcus Denker marcus at ira.uka.de




More information about the Squeak-dev mailing list