2008年7月29日火曜日

Squeak Smalltalkで順序付き辞書 改良

以前書いた順序付き辞書をちょっとだけ改良(removeを実装しただけw).

う〜ん.
まだ僕のレベルだとエレガントには書けないな・・・.

Collection subclass: #OrderedDictionary
instanceVariableNames: 'keys content'
classVariableNames: ''
poolDictionaries: ''
category: 'Ringo-Collection'

OrderedDictionary methodsFor: 'enumerating'
do: aBlock
keys do:[:v | aBlock value:v].

OrderedDictionary methodsFor: 'initialize-release'
initialize
keys := OrderedCollection new.
content := Dictionary new.


OrderedDictionary methodsFor: 'accessing'
at: key
^ content at: key! !

OrderedDictionary methodsFor: 'accessing'
at: key put: value
content at: key put: value.
(keys includes:key) ifFalse:[
keys add: key.
].
^ value.

OrderedDictionary methodsFor: 'accessing'
keys
^ keys

OrderedDictionary methodsFor: 'accessing'
values
| out |
out := WriteStream on: (Array new: keys size).
keys do:[:v |
out nextPut: (content at:v)].
^ out contents

OrderedDictionary methodsFor: 'accessing'
removeKey: key
keys remove: key.
content removeKey: key.



実行すると


x := OrderedDictionary new.
x
x at:#one put:1.
x at:#two put:2.
x values
x do:[:v | Transcript cr;show:v].

==>one
==>two

x removeKey:#one.
x removeKey:#two.
x ==> an OrderedDictionary()



0 件のコメント: