Wandering OT, starttime execution
Kyle Furlong
kylefurlong at gmail.com
Sun May 14 16:43:08 PDT 2006
Chad J wrote:
> Derek Parnell wrote:
>>
>>
>> There are already precedents for this type of coding. Not only the
>> 'unittest' idea but 'scope()' also allows us to physically separate
>> code that is executed linearly. So the concept is not foreign to D or
>> Walter.
>>
>
> While I'm at it, I'd also like to see the ability to set a variable to
> the result of some function at starttime, like so:
>
> int[] squares = initSquares();
>
> int[] initSquares()
> {
> int[] result = new int[20];
> for ( int i = 0; i < 20; i++ )
> result[i] = i * i;
> return result;
> }
>
> void main()
> {
> char[] testStr;
> for ( int i = 0; i < squares.length; i++ )
> testStr ~= toString(i)~" squared is "~toString( squares[i] ) ~
> "\n";
>
> writefln( testStr );
> }
>
> This is something I used in C# and enjoyed. Any particular reason this
> doesn't exist already? Maybe I am supposed to write my code a different
> way, if so please enlighten me. My current workaround is to use static
> ctors, but that doesn't seem as readable to me.
This is the natural functional area for template functions.
Simply change your code to this:
int[20] squares = initSquares!(int, 20)();
template initSquares(T, int C)
{
T[] initSquares()
{
T[C] result;
for ( int i = 0; i < C; i++ )
result[i] = i * i;
return result;
}
}
--
Kyle Furlong // Physics Undergrad, UCSB
"D is going wherever the D community wants it to go." - Walter Bright
More information about the Digitalmars-d
mailing list