Function calls
bearophile
bearophileHUGS at lycos.com
Tue Jan 26 23:34:20 PST 2010
I have written the following closure, to generate numbers in 1-7 from numbers in 1-5, as alternative implementation of this:
http://rosettacode.org/wiki/Seven-dice_from_Five-dice#D
auto dice7Gen(alias d5)() {
int rem = 0;
int max = 1;
int gen7() {
while (rem / 7 == max / 7) {
while (max < 7) {
int rand5 = d5() - 1;
max *= 5;
rem = 5 * rem + rand5;
}
int groups = max / 7;
if (rem >= 7 * groups) {
rem -= 7 * groups;
max -= 7 * groups;
}
}
int result = rem % 7;
rem /= 7;
max /= 7;
return result + 1;
}
return gen7;
}
Can you spot the bug? It returns an integer instead of a closure :-)
The correct last line has to be:
return &gen7;
But I think the real "bug" here is in the D2 design. In D2 calling callables without () has to be disallowed:
- & to take their reference/address
- () to call them
Otherwise syntax error at compile-time.
Only properties marked with @property are allowed to be called without (). (If you really want it, then even free functions may be allowed to be marked with @property. This probably will not cause many bugs).
This can avoid bugs and tidy the language a little more.
Bye,
bearophile
More information about the Digitalmars-d
mailing list