Dicebot on leaving D: It is anarchy driven development in all its glory.

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Aug 29 19:12:41 UTC 2018


On Wed, Aug 29, 2018 at 07:50:57PM +0200, Timon Gehr via Digitalmars-d wrote:
> On 28.08.2018 03:11, Walter Bright wrote:
> > On 8/27/2018 10:08 AM, H. S. Teoh wrote:
> > > Const in D makes sense as-is.  Though, granted, its infectiousness
> > > means its scope is actually very narrow, and as a result, we
> > > ironically can't use it in very many places, and so its touted
> > > benefits only rarely apply. :-(  Which also means that it's taking
> > > up a lot of language design real estate with not many benefits to
> > > show for it.
> > 
> > D const is of great utility if you're interested in functional
> > programming.
> 
> D const/immutable is stronger than immutability in Haskell (which is
> usually _lazy_).

This makes me wonder: is it possible to model a lazy immutable value in
D?

Likely not, if we were to take the immutability literally, since once
the variable is marked immutable and initialized, you couldn't change it
afterwards (without casting and UB).

We *might* be able to get away with a head-mutable reference to the
data, though. Say something like this:

	struct LazyImmutable(T, alias initializer)
	{
		immutable(T)* impl;
		@property T get() {
			if (impl is null)
				impl = initializer();
			return *impl;
		}
		alias get this;
	}

Seems rather cumbersome to use in practice, though.  And adds
indirection overhead to by-value types. One could possibly use emplace
to alleviate that, but still, the variable itself cannot be marked
immutable without breaking its functionality.

Which means you couldn't rely on such a wrapper type to work
transitively in complex types, unlike how immutable applies transitively
to all aggregate members: if T was an aggregate type, they couldn't be
LazyImmutable, but must be actually immutable.  Maybe this can be made
to work, but at the sacrifice of being unable to use built-in type
qualifiers like const/immutable.


T

-- 
Fact is stranger than fiction.


More information about the Digitalmars-d mailing list