The Artima Developer Community
Sponsored Link

Agile Buzz Forum
Replacing values in collections

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
James Robertson

Posts: 29924
Nickname: jarober61
Registered: Jun, 2003

David Buck, Smalltalker at large
Replacing values in collections Posted: Jan 8, 2005 6:32 AM
Reply to this message Reply

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
Latest Agile Buzz Posts
Latest Agile Buzz Posts by James Robertson
Latest Posts From David Buck - Blog

Advertisement

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.

Read: Replacing values in collections

Topic: Trying the SmalltalkDoc preview Previous Topic   Next Topic Topic: Linux/Unix fix for BottomFeeder dev

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use