Search code examples
iterationenumerationsmalltalkpharo

Perform block for each satisfied condition, otherwise perform other block


Imagine that you have to select some values and for each of them you have to evaluate a block. On the other hand if there is no value that satisfies the condition another block has to be evaluated.

Example: Consider the next method signature:

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock

This method should evaluate a block aBlock with every positive element of aCollection, but if there are no elements like that, evaluate defaultBlock. Please note that in reality the method may calculate something more complex than just positive numbers, and instead of aCollection there can be a much complex object.


Solution

  • Taking Uko's solution a bit further:

    forPositivesOf: aCollection do: aBlock otherwise: defaultBlock
        ^ (aCollection
              select: #positive
              thenCollect: aBlock
          ) ifEmpty: defaultBlock