www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - nice how D's pieces fit together

reply "anonymous" <anonymous example.com> writes:
Just a little newbie aha moment I'd like to share.

I was about to post this:

int[] f() {return [1, 2, 3];}

As far as I understand, f returns a fresh array on each call, 
and therefore, it should be safe to store the result in an 
immutable variable.

Unfortunately, this fails: immutable v = f();
"Error: cannot implicitly convert expression (f()) of type int[] 
to immutable(int[])"

I could cast explicitly, of course: auto v = cast(immutable) f();
But can the cast be avoided?
Then it struck me: The compiler doesn't know that f's return value is unknown to the rest of the world, because f isn't marked pure. And, indeed, make f pure and it just works: int[] f() pure {return [1, 2, 3];} immutable v = f(); Awesome!
Mar 14 2013
next sibling parent reply "anonymous" <anonymous example.com> writes:
On Friday, 15 March 2013 at 02:31:32 UTC, anonymous wrote:
 Then it struck me:
 The compiler doesn't know that f's return value is unknown to 
 the rest of the world, because f isn't marked pure.
 And, indeed, make f pure and it just works: int[] f() pure 
 {return [1, 2, 3];} immutable v = f();

 Awesome!
And it would be even more awesomer if std.array.array was pure ... bummer
Mar 14 2013
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Friday, March 15, 2013 03:41:14 anonymous wrote:
 On Friday, 15 March 2013 at 02:31:32 UTC, anonymous wrote:
 Then it struck me:
 The compiler doesn't know that f's return value is unknown to
 the rest of the world, because f isn't marked pure.
 And, indeed, make f pure and it just works: int[] f() pure
 {return [1, 2, 3];} immutable v = f();
 
 Awesome!
And it would be even more awesomer if std.array.array was pure ... bummer
It should be eventually, but there's still some key, low-level stuff (particularly in druntime) which isn't pure yet but should be eventually. And attribute inferrence will probably have to be improved as well for it to work. But we should get there eventually. - Jonathan M Davis
Mar 14 2013
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
anonymous:

 The compiler doesn't know that f's return value is unknown to 
 the rest of the world, because f isn't marked pure.
 And, indeed, make f pure and it just works: int[] f() pure 
 {return [1, 2, 3];} immutable v = f();

 Awesome!
"purity" seems a simple idea, but if you try to implement it "well" in a system language as D you quickly learn that it's composed of *many* parts. You have hit one of its many parts. Each of those part was invented by someone, designed, implemented (often by Hara), tested... :-) Some small parts of D purity are not yet fully implemented, you see part of them here: http://d.puremagic.com/issues/buglist.cgi?quicksearch=pure http://d.puremagic.com/issues/buglist.cgi?quicksearch=purity Bye, bearophile
Mar 14 2013