配列遊び
import std.c.stdio; void main(){ int[] a; a.length = 10; for (int i = 1; i < 10; i++){ a[i] = i; } int power_of_two(int i){ return i * i; } bool power_of_three(int i){ return ((i % 3) == 0); } int delegate(int) dg_a = &power_of_two; bool delegate(int) dg_b = &power_of_three; a = a.each(dg_a); a = a.delete_if(dg_b); a = a.compact(); foreach (int i, int x; a){ printf("%d %d\n", i, x); } } template each(T){ T[] each(T[] ary, T delegate(T) dg){ T[] rary; rary.length = ary.length; foreach (int i, T t; ary){ rary[i] = dg(t); } return rary; } } template delete_if(T){ T[] delete_if(T[] ary, bool delegate(T) dg){ T[] rary; rary.length = ary.length; foreach (int i, T t; ary){ if (!dg(t)){ rary[i] = t; } } return rary; } } template compact(T){ T[] compact(T[] ary){ T[] rary; rary.length = ary.length; int cnt = 0; foreach (T t; ary){ if (t != T.init){ rary[cnt] = t; cnt++; } } rary.length = cnt; return rary; } }
0 1 1 4 2 16 3 25 4 49 5 64
まあよく考えなくてもこんなのわざわざtemplateにせずとも自分で書けばいいしな…とか思った奴は正座。いますぐだ。