Content deleted Content added
m Removed talk section irrelevant to the article. Discussion of naming conventions in the language is not for here. |
|||
Line 49:
: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. --[[User:CyberShadow|Vladimir]] ([[User talk:CyberShadow|talk]]) 11:45, 6 November 2010 (UTC)
::It does compile, but by default functions are (weakly) pure if they don't access any global or static mutable data. They are free to access non-mutable (i.e. const, immutable, or static initialized module / class / thread data) and non-global-non-static data, this includes the parent function data. To ensure somehow functional safety, one need strong purity, this can be done by marking a function as immutable, as well not using transitively mutable references in input and output arguments.
<source lang="D">
int[] a1 = [0,1,2,3,4,5,6,7,8,9];
int[] a2 = [6,7,8,9];
int pivot = 5;
pure int mysum(int a, int b) immutable // pure function
{
if (b <= pivot) // ref to enclosing-scope
return a + b;
else
return a;
}
</source>
::will not compile, and compiler will report the issue:
<source>
a.d:10:18: error: immutable function 'a.main.mysum' cannot access mutable data 'pivot'
10 | if (b <= pivot) // ref to enclosing-scope
</source>
If the pivot is made const or immutable, it will compile. In this sense the function will become strongly pure, but only during current execution of the scope. The context will be takes implicitly. https://dlang.org/spec/function.html#pure-functions provides some extra details, but details of pure functions inside other functions is not really well explained. [[Special:Contributions/81.6.34.172|81.6.34.172]] ([[User talk:81.6.34.172|talk]]) 20:15, 29 April 2020 (UTC)
== Pull the C# reference until examples? ==
|