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

北慕城南 提交于 2019-12-11 04:03:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/50071106/creating-a-key-value-message-in-smalltalk-pharo-that-take-blocks-as-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!