[SML 7608] Re: クロージャ

Hiroshi Umeoka umrlazybind @ gmail.com
2009年 7月 5日 (日) 19:40:16 JST


濱崎さん

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

2009/07/05 16:24 に 濱崎治<osamu.hamasaki @ gmail.com> さんは書きました:
> 濱崎です。
> 2009/07/05 6:39 Hiroshi Umeoka <umrlazybind @ gmail.com>:
>>
>> おはようございます、梅岡です。
>
> <中略>
>>
>> amount
>> がインスタンス変数のように機能しますね。まるでブロックがオブジェクトのように振る舞っています。クロージャって面白いっ、と単純に思いました。
>
> 梅岡さんの提示された例題を見て、ふと「こんなこと出来るかなあ」と思いついて
> やってみたら上手く動いたので、ご紹介します。
> -------------- ここから -----------------
> | accountCreater anAccount newBlockCreater newBlock method |
> 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: 500) printString.
> Transcript cr; show: ((anAccount at: #deposit) value: 300) printString.
> newBlockCreater :=
> [| balance |
> [balance := 0.
> balance yourself]
> yourself].
>
> newBlock := newBlockCreater value.
> method := newBlock method.
> newBlock
> setMethod: method
> outerContext: (anAccount at: #balance) outerContext
> copiedValues: (anAccount at: #balance) copiedValues.
> anAccount at: #reset put: newBlock.
> Transcript cr; show: (anAccount at: #reset) value printString.
> ^anAccount
> -------------- ここまで -----------------
> 以前のSmalltalk勉強会@京都で、「クラスがメソッドを保持しているのは、
> メモリの節約のためで」なんていうお話がありましたが、このプログラムでは
> オブジェクト自身がメソッドを持っていて、さらにオブジェクトを生成した後に
> メソッドを追加しています。がんばって書けば、インスタンス変数(?)を追加
> することも恐らく可能だと思います。
> --
>
> Osamu Hamasaki
>
>


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