Lazy functions, lazy arrays

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 20 09:42:07 PDT 2015


On Friday, 20 March 2015 at 16:01:51 UTC, Dennis Ritchie wrote:
> On Friday, 20 March 2015 at 14:27:06 UTC, John Colvin wrote:
>> I made a mistake about the static variable and thread-local 
>> storage.
>>
>> immutable(int)[] factorials()() @property
>> {
>>    static immutable int[N] results = memoizeFactorials(N);
>>    return results[];
>> }
>>
>> is the correct way to do it if you have to.
>>
>> Still, it's totally not worth doing for such a short array.
>
> Thank you, but I can not figure out how I do this:
>
> import std.stdio;
>
> enum N = 12;
>
> immutable(int)[] factorials()() @property
> {
>     static immutable int[N] results = memoizeFactorials(N);
>     return results[];
> }
>
> int[] memoizeFactorials(int n)
> {
>     if (!__ctfe)
>         // Make sure that this function is never called at run 
> time
> 		assert(false);
>
>     int[] result = new int[n];
>
>     result[0] = 1;
>
>     foreach (i; 1 .. n)
>         result[i] = result[i - 1] * i;
>
>     return result;
> }
>
> void main()
> {
> 	bool flag;
> 	if (flag) {
> 		factorials();
> 		writeln(factorials[10]); // 3628800
> 	}
> 	else
> 		writeln(factorials[10]); // range violation(35)
> }

Both of those work for me on multiple dmd versions including git 
HEAD.


More information about the Digitalmars-d-learn mailing list