Amusing D facts: typesafe variadic arrays are lazy!
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Oct 13 08:30:08 PDT 2009
downs wrote:
> Did you know the following code compiles?
>
>> module test;
>>
>> import std.stdio;
>>
>> void Assert(bool cond, string delegate()[] dgs...) {
>> debug if (!cond) {
>> string str;
>> foreach (dg; dgs) str ~= dg();
>> throw new Exception(str);
>> }
>> }
>>
>> void main() {
>> Assert(false, "O hai thar! ");
>> }
>
>
> It's true! :)
Gosh!!! What's happening over here? I even tried this:
import std.stdio;
void Assert(bool cond, string delegate()[] dgs...) {
if (!cond) {
string str;
foreach (dg; dgs) str ~= dg();
throw new Exception(str);
}
}
string fun(string a, string b) {
writeln("Concatenating...");
return a ~ b;
}
void main() {
Assert(true, fun("O hai thar! ", "wyda"));
Assert(false, fun("O hai thar! ", "wyda"));
}
This example only prints "Concatenatning..." once, meaning that fun is
also lazified!!!
This is very exciting! The fact that this little anomaly hasn't caused
trouble is a good sign it could actually replace lazy!
Andrei
More information about the Digitalmars-d
mailing list