Wikipedia purity example and discussion

Lutger lutger.blijdestijn at gmail.com
Sat Nov 6 05:09:07 PDT 2010


Vladimir Panteleev wrote:

> A while ago, someone added an example with pure functions to Wikipedia's
> D article:
> 
> http://en.wikipedia.org/wiki/D_(programming_language)#Functional
> 
> Someone on the talk page asked why does the program compile despite that
> mySum accesses a variable in its enclosing function:
> 
> 
http://en.wikipedia.org/wiki/Talk:D_(programming_language)#Purity_of_mySum_function_in_the_.22Functional.22_section_.281.1.4.29
> 
> I replied with:
> 
>> The code indeed compiles. I think that the idea is that nested functions
>> have a hidden argument - a pointer to their enclosing scope (main's
>> local variables). However, that doesn't explain why the code continues
>> to compile when pivot is moved outside main(), or if you add a call to a
>> non-pure function in mySum - these sound like compiler bugs.
> 
> I don't know much about purity, so I thought someone could shed some
> light on this?
> 

I think the wikipedia example is wrong and that it compiles is related to 
these bugs:

http://d.puremagic.com/issues/show_bug.cgi?id=5006
http://d.puremagic.com/issues/show_bug.cgi?id=4640

if mysum is instead declared in this way as suggested by bug 4640 dmd does 
give an error:

int mysum(int a, int b) pure ...

Error: pure nested function 'mysum' cannot access mutable data 'pivot'



More information about the Digitalmars-d mailing list