Saturday, 31 October 2015

Iterators - OO Computing with Smalltalk, Ch23.5

If we wish to perform the same operation on all the elements in a collection at once, we use an enumerating message.

e.g. do: or detect:ifNone:

e.g. myCollection do: [ :each | each doSomething ]

do: is an example of a generalised iterator

a do: block will reference all the member elements of a Set when used on a set, and all the member elements of a Dictionary when used on a dictionary.

e.g. x := mySet detect: [ :each | each = 34 ] ifNone: [ nil ]

x is true if there is a member of the set which is 34, and returns nil if there is no matching member

In a dictionary, detect:ifNone: would check values, not keys.

No comments:

Post a Comment