Using pure to create immutable

Jonathan M Davis jmdavisProg at gmx.com
Thu Sep 22 14:18:29 PDT 2011


On Thursday, September 22, 2011 14:10 Steven Schveighoffer wrote:
> On Thu, 22 Sep 2011 17:03:08 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
> 
> wrote:
> > In any case, in order for a function to be able to have its return value
> > implicitly value implicitly cast to immutable, it must pure and all of
> > its
> > arguments must be immutable or implicitly convertible to immutable (or -
> > if
> > the compiler is ever improved to treat pure functions with const
> > parameters
> > and immutable arguments the same way - the requirement would be that the
> > function must be pure and all of its _arguments_ must be immutable or
> > implicitly convertible to immutable).
> 
> No, the parameter types can be const, and can accept mutable arguments.
> The main point is, the return value has to be proven to be *unique*. The
> only way to do this with pure functions is to prove that the result is
> *not* a subset of the parameters. That's all.
> 
> Observe:
> 
> char[] foo(const(char)[] x) pure {...}
> 
> There is no way to write the body of this function such that the return
> value is a substring of x. So you are guaranteed that the result is *new
> memory*, and since it cannot be stored globally anywhere (per pure rules),
> it's guaranteed to be unique, and should be implicitly castable to
> immutable.
> 
> Even if you pass a char[] into foo.

Hmmmm. You're right. Bleh. This is overly complicated. It works, but sorting 
it out is a pain. And trying to explain to newbies why and when a function can 
have its return value implicitly converted to immutable... Well, it's going to 
be an issue - just like with strong purity, but in that case at least, we can 
pretty much just let the compiler optimize where it's going to optimize and 
not generally worry about what's strong or weakly pure unless you're really 
trying to optimize code. In this case, however, programmers are going to need 
to understand in order to use it properly.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list