Talk:D (programming language): Difference between revisions

Content deleted Content added
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags
Line 14:
I am not a D programmer, so I may misunderstand the language's semantics, but I am confused about how the mySum function could be considered pure:
 
<sourcesyntaxhighlight lang="D">
int main()
{
Line 28:
return a;
}
</syntaxhighlight>
</source>
 
The value mySum produces depends on the value of pivot from the enclosing scope. If the numerical value of pivot in mySum was fixed at the time mySum is defined, then mySum would be only depend on its arguments, and could arguably be called a pure function, but from what I infer from the section on nested functions on [http://www.digitalmars.com/d/2.0/function.htm the function page] of D's reference manual, the value of pivot in mySum is the value of pivot in the enclosing scope at the time mySum is called.
Line 34:
So I would expect that:
 
<sourcesyntaxhighlight lang="D">
pivot = 4;
mySum(3, 5);
</syntaxhighlight>
</source>
would yield 3, but
 
<sourcesyntaxhighlight lang="D">
pivot = 5;
mySum(3, 5);
</syntaxhighlight>
</source>
would yield 8
 
Line 53:
::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.
 
<sourcesyntaxhighlight lang="D">
int[] a1 = [0,1,2,3,4,5,6,7,8,9];
int[] a2 = [6,7,8,9];
Line 65:
return a;
}
</syntaxhighlight>
</source>
::will not compile, and compiler will report the issue:
 
<syntaxhighlight>
<source>
a.d:10:18: error: immutable function 'a.main.mysum' cannot access mutable data 'pivot'
10 | if (b <= pivot) // ref to enclosing-scope
</syntaxhighlight>
</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)