| 1 |
// Create a constant array of long or ulong-sized items. Needs to be cast back to |
|---|
| 2 |
// long[] or ulong[]. |
|---|
| 3 |
template generateArrayAsChar(alias entry, int n) |
|---|
| 4 |
{ |
|---|
| 5 |
static if ( entry!(0).sizeof == dchar.sizeof) { |
|---|
| 6 |
// int or uint sized items |
|---|
| 7 |
static if (n==0) { |
|---|
| 8 |
const dchar [] generateArrayAsChar = ""d ~ cast(dchar)entry!(n); |
|---|
| 9 |
} else { |
|---|
| 10 |
const dchar[] generateArrayAsChar = generateArrayAsChar!(entry, n-1) ~ cast(dchar)entry!(n); |
|---|
| 11 |
} |
|---|
| 12 |
} else static if ( entry!(0).sizeof == 2*dchar.sizeof) { |
|---|
| 13 |
// long or ulong sized items |
|---|
| 14 |
static if (n==0) { |
|---|
| 15 |
const dchar [] generateArrayAsChar = ""d |
|---|
| 16 |
~ cast(dchar)entry!(n) ~ cast(dchar)(entry!(n)>>>32); |
|---|
| 17 |
} else { |
|---|
| 18 |
const dchar[] generateArrayAsChar = generateArrayAsChar!(entry, n-1) |
|---|
| 19 |
~ cast(dchar)entry!(n) ~ cast(dchar)(entry!(n)>>32); |
|---|
| 20 |
} |
|---|
| 21 |
} |
|---|
| 22 |
} |
|---|
| 23 |
|
|---|
| 24 |
template generateArray(alias entry, int n) |
|---|
| 25 |
{ |
|---|
| 26 |
const typeof(entry!(0)) [] generateArray = cast(typeof(entry!(0)) [])generateArrayAsChar!(entry, n); |
|---|
| 27 |
} |
|---|
| 28 |
|
|---|
| 29 |
// The ubiquitous factorial function |
|---|
| 30 |
// |
|---|
| 31 |
// Returns correct value for n=0 (factorial!(0)=1). |
|---|
| 32 |
template factorial(int n) |
|---|
| 33 |
{ |
|---|
| 34 |
static if (n<2) const uint factorial = 1; |
|---|
| 35 |
else const uint factorial = n * factorial!(n-1); |
|---|
| 36 |
} |
|---|
| 37 |
|
|---|
| 38 |
// Make an array of all the factorials from 0 to 13 (14!> ulong.max) |
|---|
| 39 |
const smallfactorials = generateArray!(factorial, 13); |
|---|
| 40 |
|
|---|
| 41 |
|
|---|
| 42 |
/+ |
|---|
| 43 |
// Make an array of all the factorials from 0 to 20 (21!> ulong.max) |
|---|
| 44 |
const ulong [] smallfactorials; |
|---|
| 45 |
static this() |
|---|
| 46 |
{ |
|---|
| 47 |
smallfactorials = cast(uint []) generateArrayAsChar!(factorial, 20); |
|---|
| 48 |
} |
|---|
| 49 |
+/ |
|---|
| 50 |
import std.stdio; |
|---|
| 51 |
|
|---|
| 52 |
void main() |
|---|
| 53 |
{ |
|---|
| 54 |
for (int i=0; i<smallfactorials.length; ++i) { |
|---|
| 55 |
writefln(i, " ", smallfactorials[i]); |
|---|
| 56 |
} |
|---|
| 57 |
} |
|---|