March 20, 2015 Re: Lazy functions, lazy arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to John Colvin | 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)
}
|
March 20, 2015 Re: Lazy functions, lazy arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dennis Ritchie | 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.
|
Copyright © 1999-2021 by the D Language Foundation