Using pure to create immutable

Jonathan M Davis jmdavisProg at gmx.com
Thu Sep 22 13:15:20 PDT 2011


On Thursday, September 22, 2011 16:09:29 Steven Schveighoffer wrote:
> On Thu, 22 Sep 2011 15:44:21 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
> 
> wrote:
> > On Thursday, September 22, 2011 23:36:40 Dmitry Olshansky wrote:
> >> On 22.09.2011 22:53, Jesse Phillips wrote:
> >> > The discussion on Reddit brought to my attention that pure
> >> > functions
> >> 
> >> can
> >> 
> >> > return and assign to an immutable.
> >> 
> >> http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutab
> >> il
> >> 
> >> > ity_in_d/c2lsgek
> >> > 
> >> > I am trying to modify the example request to make use of this, but
> >> 
> >> have
> >> 
> >> > failed.
> >> 
> >> http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutab
> >> il
> >> 
> >> > ity_in_d/c2lrfpm
> >> > 
> >> > test.d(4): Error: cannot implicitly convert expression
> >> > (makeFromArray([1,2,3])) of type test.List!(int).List to
> >> > immutable(List)
> >> > 
> >> > Is this a bug? I can't identify where this issue would lie (works
> >> > with
> >> > inheritance and templating).
> >> 
> >> Maybe:
> >> -------------------------<<<<<<<<<<
> >> 
> >>   List!T makeFromArray(T)(immutable T[] array) pure {
> >>   
> >> >     if (array.length == 0) { return null; }
> >> >     
> >> >     auto result = new Cons!T(array[0], null);
> >> >     auto end = result;
> >> >     
> >> >     for (int i = 1; i<  array.length; ++i) {
> >> >     
> >> >        end.tail_ = new Cons!T(array[i], null);
> >> >        end = end.tail_;
> >> >     
> >> >     }
> >> >     
> >> >     return result;
> >> > 
> >> > }
> >> 
> >> If I'm not mistaken only strongly pure functions are working.h
> > 
> > Which would make sense. The only reason that it can implicitly cast to
> > immutable is because it _knows_ that there are no other mutable
> > references to
> > that data, and for it to be able to know that, the function must be
> > strongly
> > pure.
> 
> Technically, something like this could be cast to immutable:
> 
> T[] foo(const(T)[] arg) pure
> 
> Since it can be proven that the result is new data.
> 
> So it doesn't *need* to be strong-pure.

Yes, you can always cast to immutable, but unless the compiler can _prove_ 
that the return value can be safely cast to immutable, it won't do it 
implicitly, and the function needs to be strongly pure to do that.

Now, if the compiler were improved to consider that function strongly pure 
when it's passed an immutable argument, then it would work in that case, but 
until that happens, it can't do that, and even then, it would only work if the 
argument passed to it were immutable rather than mutable or const.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list