lazy variables
aliak
something at something.com
Thu Oct 18 16:10:04 UTC 2018
On Thursday, 18 October 2018 at 14:16:56 UTC, Simen Kjærås wrote:
> On Wednesday, 17 October 2018 at 07:32:37 UTC, aliak wrote:
>> Hi,
>>
>> Is there any notion of lazy vars in D (i see that there're
>> parameters)?
>
> What the language doesn't provide, it generally provides the
> tools to make:
>
> struct Lazy(T) {
> T delegate() _payload;
> this(lazy T t) {
> _payload = () => t;
> }
> T get() {
> return _payload();
> }
> alias get this;
> }
>
> int fun() {
> n++;
> return 2;
> }
>
> int n;
>
> unittest {
> Lazy!int a = 1 + fun();
> assert(n == 0); // Ensure fun hasn't been called.
> auto b = a + 2;
> assert(b == 5); // Ensure calculation is correct.
> assert(n == 1); // Ensure fun has been called.
> }
>
> --
> Simen
yes! perfect! Thank you
More information about the Digitalmars-d-learn
mailing list