Using pure to create immutable
Steven Schveighoffer
schveiguy at yahoo.com
Thu Sep 22 14:10:01 PDT 2011
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.
-Steve
More information about the Digitalmars-d-learn
mailing list