在Smalltalk / Pharo中创建一个以块为参数的键值消息 [英] Creating a key value message in Smalltalk/Pharo that take blocks as argument
问题描述
我有一个方案,其中一个类包含两个互斥的实例变量。一次只能实例化一个。确切地说,我有一个Promise类(试图向Pharo中添加Promise),它包含promiseError和promiseValue实例变量。然后,我想实现方法 then:catch:。
此方法应如下工作:
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
这应该类似于try-catch块。
This should work analogously to a try-catch block.
推荐答案
您尝试过这种方法吗?
then: aBlock catch: anotherBlock
promiseError notNil ifTrue: [^anotherBlock value: promiseError].
^aBlock value: promiseValue
请注意,代码不依赖 promiseValue
是 nil
还是不是,因为 nil
可能是承诺
。但是,如果出现某些 promiseError
,我们知道 promise
失败了,否则成功了。
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.
当然,这里我假定承诺
成功或未成功完成后,将发送此消息。如果不是这种情况,则代码应在 promise
信号量上等待。
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.
这篇关于在Smalltalk / Pharo中创建一个以块为参数的键值消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!