Squeak システムの Smalltalk で switch/case 式

Python スレに端を発した switch/case 文の話。ゲンゴァー未満の私は、どっちかというと Googler なのでw、検索で見つけたこちらのCamp Smalltalk の記事をパクって、Squeak システムの Smalltalk に組み込んでみました。

char
char _ $b. ^ char switch caseIs: $a then: [1]; caseIs: $b then: [2]; otherwise: [3] "=> 2 "
char
char _ $b. ^ char switch caseIsAny: #($a $b $c) then: [1]; caseIs: $d then: [2]; otherwise: [3] "=> 1 "


定義はこちら。

'From SqueakNihongo6.1 of 17 April 2004 [latest update: #0]'!
Object subclass: #Case
   instanceVariableNames: 'criterion satisfied response '
   classVariableNames: ''
   poolDictionaries: ''
   category: 'Kernel-Objects'!

!Object methodsFor: 'casing'!
switch
   ^ Case for: self! !

!Case methodsFor: 'accessing'!
satisfied
   ^ satisfied ifNil: [satisfied _ false]! !

!Case methodsFor: 'casing'!
case: testBlock then: execBlock
   (self satisfied not and: [testBlock value: criterion])
     ifTrue: [
       satisfied _ true.
       response _ execBlock value]! !

!Case methodsFor: 'casing'!
caseIs: testObject then: execBlock
   self case: [: caseCriterion | testObject = caseCriterion] then: execBlock! !

!Case methodsFor: 'casing'!
caseIsAny: testCollection then: execBlock
   self case: [: caseCriterion | testCollection includes: caseCriterion] then: execBlock! !

!Case methodsFor: 'casing'!
otherwise: execBlock
   self satisfied not ifTrue: [response _ execBlock value].
   ^ response! !

!Case methodsFor: 'private'!
criterion: anObject
   criterion _ anObject! !

!Case class methodsFor: 'instance creation'!
for: anObject
   ^ self new criterion: anObject; yourself! !

もっとも Squeak に限って言えば、前身の Apple Smalltalk 時代にカーリーブレイス(中括弧)を使った #caseOf: 、#caseOf:otherwise: がラリー・テスラーの手により設けられているので(万一、無性に欲しくなったとしてもw)わざわざ組むには及びません。

char
char _ $b. ^ char caseOf: { [$a] -> [1]. [$b] -> [2]} otherwise: [3] "=> 2 "