recursive function call at compile time
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Dec 16 12:14:37 PST 2012
>
>
> When you instantiate MyStruct!5, it tries to define ret, so it
> instantiates MyStruct!4, MyStruct!3, ... and so on. You have to put a
> static if or something else to stop that.
>
Like this:
import std.stdio;
struct MyStruct(uint K) if (K > 0) // Only to disable direct creation for
K==0
{
real[K] data;
static if (K > 1) // getSmaller only exists for K > 1
MyStruct!(K-1) getSmaller()
{
MyStruct!(K-1) ret;
foreach( no, ref d; ret.data )
d = data[no];
return ret;
}
real recursionAlgo()
{
static if( K == 1 ) return data[0];
else
{
real sum = 0;
foreach( i; 1 .. K )
sum += getSmaller().recursionAlgo();
return sum;
}
}
}
void main()
{
MyStruct!(5) a;
a.data = [ 1, 2, 3, 4, 5 ];
writeln( a.recursionAlgo() ); // 24
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20121216/ac96c8f8/attachment.html>
More information about the Digitalmars-d-learn
mailing list