謎's キッチン

謎のひとりごと。Amazon欲しい物リストはこちら: https://www.amazon.co.jp/hz/wishlist/ls/CCPOV7C6JTD2

レキシカルクロージャktkr

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