This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Replacing values in collections
Feed Title: David Buck - Blog
Feed URL: http://www.cincomsmalltalk.com/rssBlog/buck-rss.xml
Feed Description: Smalltalk can do that
It's funny how you can put up with annoyances for years, then one day realize that you can make it much easier. That's what Anthony Lander and I discovered the other day when we were discussing Smalltalk annoyances.
We often need to replace the value in a collection with another value. For example:
myCollection at: index put: (myCollection at: index) + 1
The corresponding C code for this is:
myCollection[index]++
Or, as real C programmers would write it: :-)
c[i]++
We can't beat C's brevity, but we can put in a better mechanism that's more general. It's trivial to write a method to allow us to say this:
myCollection at: index replaceWith: [:value | value + 1]
For dictionaries, we could also do this:
myCollection at: index replaceWith: [:value | value + 1] ifAbsent: [0]
and:
myCollection at: index replaceWith: [:value | value + 1] ifAbsentPut: [0]
Now, you can do anything you like in the replaceWith block. It's so nice having an extensible language.