Execute a block for each satisfied condition; otherwise, execute another block

Imagine that you need to select some values, and for each of them you should evaluate the block. On the other hand, if there is no value that satisfies the condition, it is necessary to evaluate another block.

Example: Consider the following method signature:

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock

This method should evaluate the block aBlockwith each positive element aCollection, but if there are no such elements, evaluate defaultBlock. Note that in fact, a method can calculate something more complicated than just positive numbers, and instead of aCollection, there can be a very complex object.

+4
source share
4 answers

Taking the Uko decision a little further:

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

A more compact version of the first option is the following, which does not instantiate a new closure and simply uses those that were received as arguments.

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock

    ^(aCollection select: [:each | each positive ]) 
         ifEmpty: defaultBlock
         ifNotEmpty: [ :collection | collection do: aBlock ]
+4
source

:

1)

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock
  (aCollection select: #positive)
    ifEmpty: [ defaultBlock value ]
    ifNotEmpty: [ :collection |
      collection do: [ :el | aBlock cull: el ] ]

, positive , aBlock , , aBlock, .

2)

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock
  | encountered |
  encountered := false.
  aCollection do: [ :el |
    el positive ifTrue: [
      encountered := true.
      aBlock cull: el ] ].

  encountered ifFalse: [
    defaultBlock value ]

, .

+1

, SequenceableCollections:

forPositivesOf: aCollection do: aBlock otherwise: defaultBlock
  (aCollection
    select: #positive
    thenCollect: [ :el | aBlock cull: el ]) ifEmpty: [ defaultBlock value ]
0

Source: https://habr.com/ru/post/1612336/


All Articles