" Smalltalk/Dictionary.st -*- Smalltalk -*- " Dictionary : Set () Dictionary noCheckAdd: anObject [ " Must be defined separately for Dictionary because findElementOrNil expects a key, not an Association. " array at: (self findElementOrNil: anObject key) put: anObject. tally := tally + 1. ] Dictionary at: key ifAbsent: aBlock [ " Answer the value associated with the key or, if the value of aBlock if the key isn't found. " | association | association := array at: (self findElementOrNil: key). ^association notNil ifTrue: [association value] ifFalse: [aBlock value] ] Dictionary at: key [ ^self at: key ifAbsent: [self errorKeyNotFound] ] Dictionary at: key put: anObject [ " Set the value at key to be anObject. If key is not found, create a new entry for key and set is value to anObject. Answer anObject. " | index association | index := self findElementOrNil: key. association := array at: index. association notNil ifTrue: [association value: anObject] ifFalse: [self atNewIndex: index put: (Association key: key value: anObject)]. ^anObject ] Dictionary includesKey: aKey [ ^(array at: (self findElementOrNil: aKey)) notNil ] Dictionary keys [ | keys | keys := Set new: array size. self keysDo: [:key | keys add: key]. ^keys ] Dictionary associationsDo: unaryBlock [ super do: unaryBlock ] Dictionary keysDo: unaryBlock [ self associationsDo: [:association | unaryBlock value: association key] ] Dictionary do: unaryBlock [ self associationsDo: [:association | unaryBlock value: association value] ] Dictionary keysAndValuesDo: binaryBlock [ self associationsDo: [:association | binaryBlock value: association key value: association value] ] Dictionary keysAndSortedValuesDo: binaryBlock [ | sc | sc := SortedCollection new: self size. sc sortBlock: [:x :y | x value < y value]. self associationsDo: [:assoc | sc add: assoc]. sc do: [:assoc | binaryBlock value: assoc key value: assoc value] ] Dictionary printElementsOn: aStream [ aStream nextPut: $(. self keysDo: [:key | aStream print: key; nextPutAll: '->'; print: (self at: key); space]. self isEmpty ifFalse: [aStream skip: -1]. aStream nextPut: $) ]