module closures01; import std.stdio; alias int delegate(int arg) Handler; Handler incBy(int n) { return delegate(int arg){ return arg + n; }; } Handler mulBy(int n) { return delegate(int arg){ return arg * n; }; } void test1() { writefln("\ntest1:\n----------------------------------------"); int x = 10, y; y = mulBy(3)(x); writefln("%d * 3 -> %d", x, y); y = mulBy(4)(x); writefln("%d * 4 -> %d", x, y); y = incBy(2)(x); writefln("%d + 2 -> %d", x, y); } void test2() { writefln("\ntest2:\n----------------------------------------"); int x = 10, y; Handler times3 = mulBy(3); Handler times4 = mulBy(4); Handler plus2 = incBy(2); y = times3(x); writefln("%d * 3 -> %d", x, y); y = times4(x); writefln("%d * 4 -> %d", x, y); y = plus2(x); writefln("%d + 2 -> %d", x, y); } public void run() { test1(); test2(); } /* **************************************** * * Compiled with: Digital Mars D Compiler v1.030 * * (Unexplainable) program output: test1: ---------------------------------------- 10 * 3 -> 30 10 * 4 -> 40 10 + 2 -> 12 test2: ---------------------------------------- 10 * 3 -> 20 10 * 4 -> 42846880 10 + 2 -> 4284698 * **************************************** */