Implicit conversions through purity

bearophile bearophileHUGS at lycos.com
Tue Apr 15 02:41:57 PDT 2014


Steve Teale:

> 1) If I attempt to compile foo2() more or less as presented 
> with 2.065, the compiler tells me:
>
> Error: '_adDupT' is not nothrow
> Error: function 'mu.foo2' is nothrow yet may throw
>
> What version is the discussion about?

This rather fastidious limitation was finally removed in the 
latest D alpha (and if you look in Bugzilla you see it has 
created few regressions).


> 2) If I have a simple program as follows, the compiler does not 
> complain about me altering the value of global a.
>
> import std.stdio;
> string a = "aaa";
>
> void foo2(in string s, ref string sOut) pure {
>     auto s2 = s.dup;
>     s2[0] = 'a';
>     sOut = cast(string) s2; // Error: cannot implicitly convert
> }
>
> void main() {
> {
>    foo2("xyz", a);
>    writeln(a);
> }

Yes, foo2 is weakly pure, but main is not tagged as pure, so main 
is free to use a global reference. If you mark main pure, your 
code will not compile even if you comment out the writeln. D is 
working as designed here.


> 3) Using a ref parameter for a pure function seems to me to be 
> a clear indication of intended side effect.

In D you can also have "const ref". A mutable ref makes the 
function "weakly pure" at best.


> Wikipedia on pure functions says it's not allowed.

D has both strongly pure and weakly pure functions (and later the 
compiler has added "const-ly pure" and another category, all 
invisible.


> Out does seem somehow different to me, since it's initial
> value is by definition throw-away.

Yes, this is true in theory. I don't know if this is also true in 
D in practice, because D out has some problems.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list