On Thursday, 18 October 2018 at 16:10:04 UTC, aliak wrote:
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

With single eval:

struct Lazy(T) {
    private T delegate() _payload;
    private T _value;
    private bool set = false;
    this(lazy T t) {
        _payload = () {
            writeln("evaled");
            return t;
        };
    }
    @property T value() {
        if (!set)
            _value = _payload();
        set = true;
        return _value;
    }

    @property void value(T newValue) {
        if (!set)
            _value = _payload();
        set = true;
        _value = newValue;
    }

    alias value this;
}

Reply via email to