On 01/27/2010 08:34 AM, bearophile wrote:
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
I disagree, I find the function calls without the () to be really
prettifying.
But maybe that's just me.
I don't think that it causes serious bugs, you would see that it's an
integer the moment you try and use it. It also helps changing code
from/to functions.
I really like this feature, and would miss it should it go away.