[SML 7609] Re: クロージャ

濱崎治 osamu.hamasaki @ gmail.com
2009年 7月 5日 (日) 21:41:22 JST


濱崎です。

2009/07/05 19:40 Hiroshi Umeoka <umrlazybind @ gmail.com>:

> 濱崎さん
>
> 梅岡です。
> フォローしていただいてありがとうございます。
> こういうオリジナル言語の作成は楽しいですね。
> このコードの後半をみて、Smalltalkのメタプログラミングにとても興味が出てきました。


はい、とても楽しいです。このところ週末はSmalltalkプログラミング三昧です。
梅岡さんも楽しいプログラミングをSmalltalkで是非。

ちなみに、インスタンス変数(?)を追加することも出来ました。

---------- ここから ----------

| accountCreater anAccount newBlockCreater newBlock newCopiedValues
oldCopiedValues |
accountCreater :=
[:initialBalance |
| balance |
balance := initialBalance.
(Dictionary new)
at: #withdraw
put:
[:amount |
balance := balance - amount.
balance yourself];
at: #deposit
put:
[ :amount |
balance := balance + amount.
balance yourself];
at: #balance
put:
[balance yourself];
yourself].

anAccount := accountCreater value: 1000.
Transcript clear.
Transcript cr; show: (anAccount at: #balance) value printString.
Transcript cr; show: ((anAccount at: #withdraw) value: 400) printString.
Transcript cr; show: ((anAccount at: #deposit) value: 300) printString.

newBlockCreater :=
[:initialId |
| balance id |
id := initialId.
[balance := 0.
id := 0] yourself.  "This is Dummy which trick compiler to make valid
copiedValues"
[id yourself]
yourself].

newBlock := newBlockCreater value: #SML.
newCopiedValues := newBlock copiedValues.
oldCopiedValues := (anAccount at: #balance) copiedValues.
oldCopiedValues
keysAndValuesDo: [:index :value | newCopiedValues at: index put: value].
newBlock
setMethod: newBlock method
outerContext: (anAccount at: #balance) outerContext
copiedValues: newCopiedValues.
anAccount
do:
[:block |
block
setMethod: block method
outerContext: block outerContext
copiedValues: newCopiedValues].
anAccount at: #id put: newBlock.

Transcript cr; show: (anAccount at: #id) value printString.
Transcript cr; show: ((anAccount at: #withdraw) value: 200) printString.
^anAccount

---------- ここまで ----------

コンパイラを騙すコードが少々必要になりましたが、
他は概ね想定していたとおりでした。

-- 

Osamu Hamasaki
-------------- next part --------------
HTMLの添付ファイルを保管しました...
URL: http://www.smalltalk.jp/pipermail/sml/attachments/20090705/1d6ae25b/attachment.html


SML メーリングリストの案内