lazy variables
Ali Çehreli
acehreli at yahoo.com
Wed Oct 17 20:32:40 UTC 2018
On 10/17/2018 12:32 AM, aliak wrote:
> Hi,
>
> Is there any notion of lazy vars in D (i see that there're parameters)?
>
> i.e:
>
> struct S {
> //...
> int y;
> //...
> }
>
> lazy S x = () {
> // do some heavy stuff
> }();
>
> if (condition) {
> func(x.y); // heavy stuff evaluated here
> }
>
> Cheers,
> - Ali
>
>
>
>
Not very clean but something like this:
import std.stdio;
struct LazyVar(alias exp) {
alias T = typeof(exp());
T value() {
static bool initialized = false;
static T val;
if (!initialized) {
val = exp();
initialized = true;
}
return val;
}
alias value this;
}
LazyVar!(() {
writeln("Doing heavy stuff");
return 42;
}) a;
void main() {
auto b = a.value; // Must specify .value or
int c = a; // must specify type of value (int).
// Otherwise, b and c have type LazyVar!(...)
// Some more usage
b = c = a;
assert(b == 42);
assert(c == 42);
}
Ali
More information about the Digitalmars-d-learn
mailing list