Pure functions as initializers for immutable structures?

Tomek Sowiński just at ask.me
Mon Oct 18 11:31:26 PDT 2010


Initializing immutable structures is a source of constant grief. Anything  
non-trivial requires instancing a mutable structure, initializing it, and  
then either casting to immutable (it's up to you to ensure no alias  
leaked) or, not to violate the type system, duplicate the whole.

Yet, if there was a situation where the alias leaking is under control,  
casting would be safe. Perhaps pure* functions are such a place. They can  
only touch the immutable world, whether through globals or through their  
parameters. So if one initializes the returned structure with a reference  
to the outside world, it will be immutable. And if you stuff the structure  
with anything mutable, it must have been created within the function's  
body, so no alias leaks.

Call me crazy, but I think it is safe to implicitly convert a pure  
function's return value to immutable. What you think?

* here by pure I mean either the old pure** when it still had immutable  
arguments, or Don's "immutably pure".
** BTW, http://www.digitalmars.com/d/2.0/function.html still says  
immutable, please update.

-- 
Tomek


More information about the Digitalmars-d mailing list