Creating a key value message in Smalltalk/Pharo that take blocks as argument
Asked Answered
B

1

2

I have a scenario where a class holds two instance variables that are mutually exclusive. That is only one can be instantiated at a time. To be precise, I have a Promise class (trying to add promises to Pharo) and it holds promiseError and promiseValue instance variables. I then want to implement the method "then: catch:". This method should work as follows:

promiseObject := [10/0] promiseValue.
promiseObject then : [ : result | Transcript crShow : result ]
catch : [ : failure | Transcript crShow : failure ] .

I got an idea on how to implement methods that take a block as an argument from method that accepts a block and the block accepts an argument. My attempt below will obviously not work but I have no idea on how to make it work.

   then:aBlock catch: anotherBlock
    |segment|
    promiseValue ifNil: [ segment := promiseError  ] ifNotNil:  [ segment := promiseValue ].
    promiseValue ifNil: [ segment := promiseValue  ] ifNotNil:  [ segment := promiseError ].
    aBlock value:segment.
    anotherBlock value: segment 

This should work analogously to a try-catch block.

Bobble answered 27/4, 2018 at 22:37 Comment(0)
N
3

Have you tried something like this?

then: aBlock catch: anotherBlock
  promiseError notNil ifTrue: [^anotherBlock value: promiseError].
  ^aBlock value: promiseValue

Note that the code does not rely on promiseValue being nil or not because nil could be a valid answer of the promise. However, if there is some promiseError, we know the promise failed, and succeeded otherwise.

Of course, here I'm assuming that this message will get sent once the promise has been successfully or unsuccessfully finished. If this is not the case, then the code should be waiting on the promise semaphore.

Nobelium answered 27/4, 2018 at 23:29 Comment(1)
I have a related question at: #50087200Bobble

© 2022 - 2024 — McMap. All rights reserved.