Amusing D facts: typesafe variadic arrays are lazy!

Don nospam at nospam.com
Tue Oct 13 08:51:19 PDT 2009


Andrei Alexandrescu wrote:
> 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

There's a bug report about it, from Sean: bugzilla 1069.




More information about the Digitalmars-d mailing list