Non-local variable: Difference between revisions

Content deleted Content added
m change source to syntaxhighlight
mNo edit summary
Line 6:
=== Nested functions === <!-- Please do NOT add the same example in other languages to this article. These two examples suffice to get the point across. Wikipedia is not a source code repository. -->
In the Python 3 example that follows there is a nested function <code>inner</code> defined in the scope of another function <code>outer</code>. The variable <code>x</code> is local to <code>outer</code>, but non-local to <code>inner</code> (nor is it global):
<syntaxhighlight lang="python3">
def outer():
x = 1
Line 17:
 
In Javascript, the locality of a variable is determined by the closest <code>var</code> statement for this variable. In the following example, <code>x</code> is local to <code>outer</code> as it contains a <code> var x</code> statement, while <code>inner</code> doesn't. Therefore, x is non-local to <code>inner</code>:
<syntaxhighlight lang="javascript">
function outer() {
var x = 1;
Line 30:
=== Anonymous functions === <!-- Please do NOT add the same example in other languages to this article. These examples suffice to get the point across. Wikipedia is not a source code repository. -->
In the Haskell example that follows the variable <code>c</code> is non-local in the anonymous function <code>\x -> x + c</code>:
<syntaxhighlight lang="haskell">
outer = let c = 1 in map (\x -> x + c) [1, 2, 3, 4, 5]
</syntaxhighlight>