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

Reply via email to