开发者

Returning messages in Smalltalk

I have a Dictionary of objects I have created in smalltalk, which I am iterating over by enumerating it based on the key/value pairs.

For value object in the dic开发者_Go百科tionary, I am calling a method on that object. Based on certain conditions, I would like for this object to be able to add a new member to dictionary, and possibly delete another one.

I've been looking at the 'Perform' and 'Messages' facilities in Smalltalk, but I'm not sure if it is even possible to do what I'm trying to do - is it possible to return a message (or multiple messages), which another object can process and perform?

For example, could my method return 'removeKey: 19' and 'add object' at the same time?

I am using GNU Smalltalk, if it matters.


When you iterate over the collection, pass the collection as part of the argument:

aCollection copy do: [:each | each doSomethingOn: aCollection]

The copy ensures that the #doSomethingOn: can alter the original collection without messing up the iteration.


A Smalltalk method can't return multiple values, but it can return a Collection containing those values:

foo
  ^ Array with: 1 with: 2.

So you return a Collection with multiple methods, and just iterate over it, sending the messages in the Collection.


The class Message can do what you want:

(Message selector: #raisedTo: argument: 2) sendTo: 3

That produces "9" when evaluated.

Note, adding or removing things from a collection while iterating over it generally is not a good idea. Try copying the collection first, iterating over the copy and modifying the original from within the block being used to iterate over the copy.


As you iterate through, add the items you want to add to aDictionary, to aTemporaryDictionaryOfAdds, and the items you want to delete to aTemporaryDictionaryOfDeletes

Then iterate through each of those, adding to and removing from aDictionary as you do.

If you add the deletes to aDictionaryOfThingsDeletedFromADictionary, you have a history, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜