JSで
function createCounter(){ var cur = 0; return { next:function(){return cur++;}, prev:function(){return cur--;} }; } var count = createCounter(); dump(count.next()); dump(count.next()); dump(count.prev());
なのをDで
import std.stdio; int delegate(...)[string] createCounter(){ int cur = 0; return ["next":(...){return cur++;},"prev":(...){return cur--;}]; } void main(){ auto count = createCounter(); writefln(count["next"]()); writefln(count["next"]()); writefln(count["prev"]()); }
と書けるはず…と思ったらセグフォ。
import std.stdio; int delegate()[string] createCounter(){ int cur = 0; return ["next":{return cur++;},"prev":{return cur--;}]; } void main(){ auto count = createCounter(); writefln(count["next"]()); writefln(count["next"]()); writefln(count["prev"]()); }
だと何故かArrayBoundsError…orz