Smalltalk - 是否有类似于 C 中的 && 的东西?

Smalltalk - is there something similar to && from C?

我必须编写一个纯对象 Smalltalk 程序,我需要在其中评估条件,直到其中一个失败。我知道在 C 中,我们可以为此使用 && 运算符,并且只有在必要时才对条件进行评估。

Smalltalk 中有类似的东西吗?

如果我理解你的问题,你正在寻找这样的东西:

[ <condition> ] whileTrue: [ <loop body> ].

#whileTrue: 当然不是关键字,您可以自己实现它(查看您选择的 Smalltalk 中的实现并获得启发:))。

如果您不需要循环而只是想寻找一种表达条件的方法,那么 #ifTrue:#ifFalse:#ifTrue:ifFalse:#ifFalse:ifTrue: 是您的朋友.示例:

myCollection isEmpty ifTrue: [ Transcript open; show: 'empty'; cr ].
myCollection isEmpty ifFalse: [ Transcript open; show: 'not empty' cr ].
myBoolean
    ifTrue: [ Transcript open; show: 'true'; cr ]
    ifFalse: [ Transcript open; show: 'false'; cr ].

条件“ing”可以通过使用&消息或and:消息来实现。

firstBooleanExpression & secondBooleanExpression
    ifTrue: [ 'do something' ].

如上所示使用 &,条件的第二部分 (secondBooleanExpression) 将被计算,而不管前半部分的计算结果是 true 还是 false

(firstBooleanExpression and: [secondBooleanExpression])
    ifTrue: [ 'do something' ].

另一方面,使用 and:,第二部分仅在前半部分计算为 true 时才计算。通常您会使用这种形式,除非您明确想要评估下半部分。

同样的原则也适用于or: