<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>numerodix blog &#187; dysfunctional</title>
	<atom:link href="http://www.matusiak.eu/numerodix/blog/index.php/category/techno-babble/dysfunctional/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.matusiak.eu/numerodix/blog</link>
	<description>A blog about nothing</description>
	<lastBuildDate>Tue, 27 Jul 2010 16:51:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>what&#8217;s in a fixed point?</title>
		<link>http://www.matusiak.eu/numerodix/blog/index.php/2008/11/09/whats-in-a-fixed-point/</link>
		<comments>http://www.matusiak.eu/numerodix/blog/index.php/2008/11/09/whats-in-a-fixed-point/#comments</comments>
		<pubDate>Sun, 09 Nov 2008 00:59:44 +0000</pubDate>
		<dc:creator>numerodix</dc:creator>
				<category><![CDATA[dysfunctional]]></category>

		<guid isPermaLink="false">http://www.matusiak.eu/numerodix/blog/?p=1645</guid>
		<description><![CDATA[The fixed point is a very intuitive idea that we know from daily life. It&#8217;s the notion that if something is a certain way, and you do something to change it, it will change. Some things you can go on changing forever by repeating the same action, but other things reach a limit beyond which [...]]]></description>
			<content:encoded><![CDATA[<p>The fixed point is a very intuitive idea that we know from daily life. It&#8217;s the notion that if something is a certain way, and you do something to change it, it will change. Some things you can go on changing forever by repeating the same action, but other things reach a limit beyond which repeating the action has no effect. Suppose you are going 50km/h in your car and you step on the brake. The car slows down. You step on the brake again, the car slows down again. But eventually the car will have come to a complete stop and stepping on the brake doesn&#8217;t do anything anymore. The point at which the action has no effect anymore has a scary math name: a fixed point.</p>
<p>It&#8217;s easy enough to write a function that finds the fixed point of another function f. You apply f to the argument and you get a value, you apply f to <em>that</em> and you get a value, you apply f to <em>that</em> and you get a value etc. And every time you check if the new value is different from the old. (Or even if it&#8217;s just sufficiently similar, <a href="http://en.wikipedia.org/wiki/Newton%27s_method">Newton-Raphson</a> says hello.) Here is how it goes:</p>
<pre>fixfinder :: (Eq a) =&gt; (a -&gt; a) -&gt; a -&gt; a
fixfinder f arg =
    let val = f arg
    in if val == arg
        then arg
        else (fixfinder f val)
&nbsp;
{-
*Main&gt; fixfinder sqrt 68
1.0
-}
&nbsp;</pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/fixfinder.hs">fixfinder.hs</a></p>
<p>We can try it on a function whose fixed point we know, like the square root. Back in school, did you ever hit the square root key on your calculator repeatedly out of shear boredom? Eventually you&#8217;d get <strong>1</strong>. (You can also take the square root of 0 and get <strong>0</strong>, the <em>second</em> fixed point, but that&#8217;s not particularly exciting.)</p>
<p>So far so good, now comes the mysterious part. The fixed point idea exists in programming, but in a different guise. In <code>Data.Function</code> there is a function called <code>fix</code>. It makes a very odd promise: to find the fixed point of a function without using a value. Que? How can you return the fixed point <em>value</em> (leaving aside for the moment the question of how you can even calculate it) if you don&#8217;t have a single <em>value</em> to begin with? Heck, without an input value you don&#8217;t even know what <em>type</em> the output is, if f is a polymorphic function.</p>
<pre>fix :: (a -&gt; a) -&gt; a
fix f = f (fix f)
&nbsp;
{-
*Main&gt; fix sqrt
*** Exception: stack overflow
-}
&nbsp;</pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/fixfunc.hs">fixfunc.hs</a></p>
<p>The function doesn&#8217;t look promising at all. It applies f, but there is no termination condition. Once you reach the fixed point (if there is one), how do you stop? It obviously can&#8217;t figure out the square root function.</p>
<p>It turns out that fix is a trick used to perform recursion in languages that don&#8217;t have a recursion primitive (ie. the compiler reaches an expression containing the name of the function in its own body and doesn&#8217;t know what to do). The trick is that you write a function expecting among other things, a function argument (fix). Then, at the point in your function where you need to recurse, you call fix. Fix then calls the function back, so it&#8217;s a sort of mutual recursion. In pure lambda calculus fix is called the <a href="http://en.wikipedia.org/wiki/Y_combinator">y-combinator</a>. The formula is so ridiculously cryptic that some have taken to tattoo it on their arms, obviously given up on remembering.</p>
<p><img class="alignnone size-full wp-image-1655" title="y_combinator" src="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/y_combinator.jpg" alt="" width="500" height="212" /></p>
<p>So what do you get out of it? Solely the fact that you get around calling the function within itself, from what I can see. And clearly that&#8217;s all it does too. How do you prevent the seemingly inevitable infinite loop? You put the termination condition in your semantic function. So you write your recursive function exactly the same, but you give it an extra argument, fix. Then, at the point of recursion, instead of calling the function, you call fix. It&#8217;s so bizarre that I&#8217;ve written out the evaluation sequence to shed some light on it.</p>
<p>Daredevil that I am, I&#8217;m using the factorial function. What&#8217;s happening here, supposedly, is that fix is computing the fixed point of fac. We can then take that result and apply it to a number, it finds the factorial, it doesn&#8217;t diverge.</p>
<p><img class="alignnone size-full wp-image-1644" title="fixpoint_derivation" src="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/fixpoint_derivation.png" alt="" width="500" height="662" /></p>
<p>What&#8217;s happening here? It looks like a sort of loop unrolling, which can clearly proceed ad infinitum, were it not for Haskell&#8217;s lazy nature. And, one can speculate, it&#8217;s unrolling the recursion exactly the number of times it needs to be expanded (but then again, evaluation with a value already does that), but how could you possibly know that before you have a <em>value</em> to calculate with? It&#8217;s not actually <em>computing</em> anything, is it? How is this any different from any old recursive function?</p>
<p>What fac really does is take one step toward the factorial. Multiply one factor, then call fix, which calls fac again. Eventually, the termination condition within fac kicks in. But that doesn&#8217;t mean we&#8217;ve found the fixed point of fac, which is <code>fac(1) = 1</code> and <code>fac(2) = 2</code>.  In fact, it seems to me we&#8217;re walking right past these two fixed points, and calling fac one last time with n=0, because how else can fac terminate?</p>
<p>There is a lot more to fixed points, there&#8217;s even something called a fixed point datatype that my small brain completely fails to comprehend. The most sane description on fix that I found is in the <a href="http://en.wikibooks.org/wiki/Haskell/Fix_and_recursion">Haskell Book</a> if you want to take a look. I wish you luck.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.matusiak.eu/numerodix/blog/index.php/2008/11/09/whats-in-a-fixed-point/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>dynamic or lexical, that is the scope</title>
		<link>http://www.matusiak.eu/numerodix/blog/index.php/2008/10/02/dynamic-lexical-scoping/</link>
		<comments>http://www.matusiak.eu/numerodix/blog/index.php/2008/10/02/dynamic-lexical-scoping/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 14:37:18 +0000</pubDate>
		<dc:creator>numerodix</dc:creator>
				<category><![CDATA[dysfunctional]]></category>

		<guid isPermaLink="false">http://www.matusiak.eu/numerodix/blog/?p=1462</guid>
		<description><![CDATA[Apologies for the awful pun on a 16th century action movie.
Do you know how in the movies, when someone has to testify they first pin his hand on a Bible and make him recite that I swear to the tell the truth, the whole truth, and nothing but the truth, so help me God litany? [...]]]></description>
			<content:encoded><![CDATA[<p><em>Apologies for the awful pun on a 16th century <a href="http://www.matusiak.eu/numerodix/blog/index.php/2006/12/18/hamlet/">action movie</a>.</em></p>
<p>Do you know how in the movies, when someone has to testify they first pin his hand on a Bible and make him recite that <em>I swear to the tell the truth, the whole truth, and nothing but the truth, so help me God</em> litany? Presumably, the god they&#8217;re talking about is the god in the book, that&#8217;s why the book is there (I bet polytheists find this very helpful). I guess they think it&#8217;s harder for people to lie after taking a pledge while handling a Bible. (Do we have any statistics on whether that works?)</p>
<p>Anyway, in a <strong>dynamic scope</strong>, there is witness called Python. He will make his pledge based on the book that they happened to shove under his hand that day. One day it could be the Bible, a week later it could be <a href="http://en.wikipedia.org/wiki/Flying_Spaghetti_Monster">The Gospel of the Flying Spaghetti Monster</a>. So that means the pledge will be somehow relative to the god in that particular book. Uneasy about one god, very comfortable with another one.</p>
<p>In a <strong>lexical scope</strong>, there is a witness called Perl. He is very emotional about his first time as a witness. And even though they give him a new book every time, he just can&#8217;t seem to notice. He makes his pledge based on the very first book they slipped him.</p>
<p>And now for a short digression into the world of programming languages. You have two scopes, one is the innermost, the other is the outer scope. There is a variable in the inner scope, but it&#8217;s bound in the outer scope. How do you evaluate this variable? There are two answers to this question.</p>
<p>Under dynamic scoping the variable gets the value that it has in the outer scope <em>at the time of evalution</em>. Under lexical scoping the variable gets the value that it has in the outer scope <em>at the time of declaration</em>.</p>
<p>That didn&#8217;t explain anything, did it? I know, read on.</p>
<h3>Who cares?</h3>
<p>This is an important question, and people rarely seem to ask it. Functions care. Named functions and unnamed functions like lambdas, blocks, closures (different languages have different names for the same thing). Anything that has a scope and can be passed around, so that&#8217;s only functions.</p>
<p>So all the blah about lexical scoping really just boils down to one little detail that has to do with how functions are evaluated. Hardly seems worth the effort, does it?</p>
<h3>Dynamic, baby</h3>
<p>Dynamic scoping is the more intuitive one. You grab the value of the variable that it has when you need to use it. That&#8217;s what&#8217;s <em>dynamic</em> about it, today this value, tomorrow another.</p>
<p>Consider this Python program. It prints the same string in three different colors. <code>output</code> is the function responsible for the actual printing. output has an inner helper function <code>colorize</code>, which performs the markup with shell escapes. Now, since <code>colorize</code> is defined in the scope of <code>output</code>, we can just reuse those bindings. I pass the string explicitly, but I don&#8217;t bother passing the color index variable. (A variable gets interpolated where there is an <code>%s</code>).</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">def</span> output<span style="color: black;">&#40;</span>color_id, s<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> colorize<span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">"<span style="color: #000099; font-weight: bold;">\\0</span>33[1;3%sm%s<span style="color: #000099; font-weight: bold;">\\0</span>33[0m"</span> % <span style="color: black;">&#40;</span>color_id, s<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">print</span> colorize<span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> e <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span>:
    output<span style="color: black;">&#40;</span>e, <span style="color: #483d8b;">"sudo make me a sandwich"</span><span style="color: black;">&#41;</span></pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/python-dynamic-scope_py">python-dynamic-scope_py</a></p>
<h3>Lexical ftw</h3>
<p>Lexiwhat? If you recall from <a href="http://www.matusiak.eu/numerodix/blog/index.php/2008/04/20/what-the-heck-is-a-closure/">last time</a>, &#8220;lexical&#8221; is a pretentious way of saying &#8220;where it was written&#8221;.</p>
<p>What this implies is that the outer binding is evaluated only the first time. After that, whatever scope the function finds itself being evaluated in, it doesn&#8217;t matter, the variable with an outer binding doesn&#8217;t change value.</p>
<p>Consider this Perl code which is exactly the same as before.</p>
<pre class="perl"><span style="color: #000000; font-weight: bold;">sub</span> output <span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">my</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$color_id</span>, <span style="color: #0000ff;">$s</span><span style="color: #66cc66;">&#41;</span> = <span style="color: #0000ff;">@_</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">sub</span> colorize <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">my</span> <span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$s</span><span style="color: #66cc66;">&#41;</span> = <span style="color: #0000ff;">@_</span>;
        <a href="http://www.perldoc.com/perl5.6/pod/func/return.html"><span style="color: #000066;">return</span></a> <span style="color: #ff0000;">"<span style="color: #000099; font-weight: bold;">\\0</span>33[1;3${color_id}m${s}<span style="color: #000099; font-weight: bold;">\\0</span>33[0m"</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <a href="http://www.perldoc.com/perl5.6/pod/func/print.html"><span style="color: #000066;">print</span></a> colorize<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"$s<span style="color: #000099; font-weight: bold;">\\n</span>"</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span><span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$e</span> = <span style="color: #cc66cc;">1</span>; <span style="color: #0000ff;">$e</span> &lt; <span style="color: #cc66cc;">4</span>; <span style="color: #0000ff;">$e</span>++<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    output<span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$e</span>, <span style="color: #ff0000;">"sudo make me a sandwich"</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/perl-lexical-scope_pl">perl-lexical-scope_pl</a></p>
<p>How do you think it evaluates?</p>
<p><img class="alignnone size-full wp-image-1459" title="python-perl-scoping" src="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/python-perl-scoping.png" alt="" width="232" height="145" /></p>
<p>Oh no, it&#8217;s broken! Why? Because the first time <code>colorize</code> is evaluated, the value of <code>${color_id}</code> is recorded and stored for all eternity. The term <em>lexical</em> in this example isn&#8217;t helpful at all, because the function is *always* evaluated where it was declared, it&#8217;s not passed to some other place where the value of <code>${color_id}</code> could have been decided by someone other than <code>output</code>. &#8216;pedia says lexical scoping is also called <a href="http://en.wikipedia.org/wiki/Scope_(programming)">static scoping</a>, which makes more sense here.</p>
<p>Interestingly, in the language of tweaks that is Perl you can replace <code>my</code> with <code>local</code> on line 2 and you got yourself dynamic scoping! <img src='http://www.matusiak.eu/numerodix/blog/wp-includes/images/smilies/eek.png' alt=':-o' class='wp-smiley' />  The code will run as expected now.</p>
<h3>Which is better?</h3>
<p>I don&#8217;t know. I don&#8217;t have any conclusions yet. I got into the habit of writing inner functions in Python without passing in all the arguments, it&#8217;s useful sometimes when you have a lot of variables in scope. And then I got in trouble for doing the same thing in Perl.</p>
<p>In languages without assignment, they will obviously pick lexical, because it reinforces the rule of referential transparency. A variable assigned always keeps the same value.</p>
<p>You need lexical scoping to have closures. A function being defined has to be able to capture and store the values of its unbound variables. Otherwise you could pass it to some other scope that doesn&#8217;t have bindings for variables with those names, and then what?</p>
<p>But you know what? Python has closures anyway. Here, <code>colorize</code> is defined inside <code>output</code>, but it&#8217;s not called. It passes back to the loop, and it&#8217;s called there. But that scope doesn&#8217;t have a binding for <code>color_id</code>! And yet it still works.</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">def</span> output<span style="color: black;">&#40;</span>color_id<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> colorize<span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">"<span style="color: #000099; font-weight: bold;">\\0</span>33[1;3%sm%s<span style="color: #000099; font-weight: bold;">\\0</span>33[0m"</span> % <span style="color: black;">&#40;</span>color_id, s<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">return</span> colorize
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> e <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span>:
    f = output<span style="color: black;">&#40;</span>e<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> f<span style="color: black;">&#40;</span><span style="color: #483d8b;">"sudo make me a sandwich"</span><span style="color: black;">&#41;</span>
&nbsp;</pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/python-lessdynamic-scope_py">python-lessdynamic-scope_py</a></p>
<p>If you try the same thing with Perl and <code>local</code> in place of <code>my</code>, and set <code>$color_id</code> to <code>$e</code>, it works too.</p>
<p>So at least for Python and Perl, you can&#8217;t reasonably say &#8220;dynamic scoping&#8221; or &#8220;lexical scoping&#8221;. They do a bit of both. So why is that? Are the concepts dynamic and lexical just too simplistic to use in the &#8220;real world&#8221;?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.matusiak.eu/numerodix/blog/index.php/2008/10/02/dynamic-lexical-scoping/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>what the heck is a closure?</title>
		<link>http://www.matusiak.eu/numerodix/blog/index.php/2008/04/20/what-the-heck-is-a-closure/</link>
		<comments>http://www.matusiak.eu/numerodix/blog/index.php/2008/04/20/what-the-heck-is-a-closure/#comments</comments>
		<pubDate>Sun, 20 Apr 2008 00:11:38 +0000</pubDate>
		<dc:creator>numerodix</dc:creator>
				<category><![CDATA[dysfunctional]]></category>

		<guid isPermaLink="false">http://www.matusiak.eu/numerodix/blog/?p=963</guid>
		<description><![CDATA[That&#8217;s a question that&#8217;s been bugging me for months now. It&#8217;s so vexing to try to find something out and not getting it. All the more so when you look it up in a couple of different places and the answers don&#8217;t seem to have much to do with each other. Obviously, once you have [...]]]></description>
			<content:encoded><![CDATA[<p>That&#8217;s a question that&#8217;s been bugging me for months now. It&#8217;s so vexing to try to find something out and not getting it. All the more so when you look it up in a couple of different places and the answers don&#8217;t seem to have much to do with each other. Obviously, once you have the big picture, all those answers intersect in a meaningful place, but while you&#8217;re still hunting for it, that&#8217;s not helpful at all.</p>
<p>I put this question to a wizard and the answer was (not an exact quote):</p>
<blockquote><p>A function whose free variables have been bound.</p>
</blockquote>
<p>Don&#8217;t you love to get a definition in terms of other terms you&#8217;re not particularly comfortable with? Just like a math textbook. This answer confused me, because I couldn&#8217;t think of a case that I had seen where that <em>wasn&#8217;t</em> the case, so I thought I must be missing something. The Python answer is very simple:</p>
<blockquote><p>A nested function.</p>
</blockquote>
<p>It&#8217;s sad, but one good answer is enough. When you can&#8217;t get that, sometimes you end up stacking up several unclear answers and hoping you can piece it all together. And that can very well fail.</p>
<p>I read <a href="http://c2.com/cgi/wiki?LexicalClosure">a definition</a> today that finally made it clear to me. It&#8217;s not the simplest and far from the most intuitive description. In fact, it <em>too</em> reads like a math textbook. But it&#8217;s simply what I needed to hear in words that would speak to me.</p>
<blockquote><p>A lexical closure, often referred to just as a <em>closure</em>, is a function that can refer to and alter the values of bindings established by binding forms that textually include the function definition.</p>
</blockquote>
<p>I read it about 3 times, forwards and backwards, carefully making sure that as I was lining up all the pieces in my mind, they were all in agreement with each other. And once I verified that, and double checked it, I felt so relieved. Finally!</p>
<p>I can&#8217;t follow the Common Lisp example that follows on that page, but scroll down and you find a piece of code that is much simpler.</p>
<p>
<pre class="lisp"><span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>foo x<span style="color: #66cc66;">&#41;</span>
	<span style="color: #66cc66;">&#40;</span>define <span style="color: #66cc66;">&#40;</span>bar y<span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#40;</span>+ x y<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
	bar<span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #66cc66;">&#40;</span>foo <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #cc66cc;">5</span> =&gt; <span style="color: #cc66cc;">6</span>
<span style="color: #66cc66;">&#40;</span>foo <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #cc66cc;">5</span> =&gt; <span style="color: #cc66cc;">7</span></pre>
<p><i>Download this code: </i><a href="http://www.matusiak.eu/numerodix/blog/wp-content/uploads/closure.lisp">closure.lisp</a></p>
</p>
<p>What&#8217;s going on here? First there is a function being defined. Its name is <code>foo</code> and it takes a parameter <code>x</code>. Now, once we enter the body of this function <code>foo</code>, straight away we have another function definition &#8211; a nested function. This inner function is called <code>bar</code> and takes a parameter <code>y</code>. Then comes the body of the function <code>bar</code>, which says &#8220;add variables <code>x</code> and <code>y</code>&#8220;. And then? Follow the indentation (or the parentheses). We have now exited the function definition of <code>bar</code> and we&#8217;re back in the body of <code>foo</code>, which says &#8220;the value <code>bar</code>&#8220;, so that&#8217;s the return value of <code>foo</code>: the function <code>bar</code>.</p>
<p>In this example, <code>bar</code> is the closure. Just for a second, look back at how <code>bar</code> is defined in isolation, don&#8217;t look at the other code. It adds two variables: <code>y</code>, which is the formal parameter to <code>bar</code>, and <code>x</code>. How does <code>x</code> receive its value? It doesn&#8217;t. Not inside of <code>bar</code>! But if you look at <code>foo</code> in its entirety, you see that <code>x</code> is the formal parameter to <code>foo</code>. Aha! So the value of <code>x</code>, which is set inside of <code>foo</code>, carries through to the inner function <code>bar</code>.</p>
<p>Can we square this code with the answers quoted earlier? Let&#8217;s try.</p>
<p><em>A function whose free variables have been bound.</em> &#8211; <em>A function</em>, in this case <code>bar</code>. <em>Free variables</em>, in this case <code>x</code>. <em>Bound</em>, in this case defined as the formal parameter <code>x</code> to the function <code>foo</code>.</p>
<p><em>A nested function.</em> &#8211; The function <code>bar</code>.</p>
<p><em>A lexical closure, often referred to just as a closure, is a function that can refer to and alter the values of bindings established by binding forms that textually include the function definition.</em> &#8211; <em>A function</em>, in this case <code>bar</code>. <em>That can refer to and alter</em>, in this case <code>bar</code> refers to the variable <code>x</code>. <em>values of bindings</em>, in this case the value of the bound variable <code>x</code>. <em>established by binding forms</em>, in this case the body of the function <code>foo</code>. <em>that textually include the function definition</em>, in this case <code>foo</code> includes the function definition of <code>bar</code>.</p>
<p>So yes, they all make sense. If you understand what it&#8217;s all about. <img src='http://www.matusiak.eu/numerodix/blog/wp-includes/images/smilies/lala.png' alt=':/' class='wp-smiley' /> </p>
<p>Let&#8217;s return to the code example. We now call the function <code>foo</code> with argument <code>1</code>. As we enter <code>foo</code>, <code>x</code> is bound to <code>1</code>. We now define the function <code>bar</code> and return it, because that is the return value of <code>foo</code>. So now we have the function <code>bar</code>, which takes one argument. We give it the argument <code>5</code>. As we enter bar, <code>y</code> is bound to <code>5</code>. And <code>x</code>? Is it an undefined argument, since it&#8217;s not defined inside <code>bar</code>? No, it&#8217;s bound *from before*, from when <code>foo</code> was called. So now we add <code>x</code> and <code>y</code>.</p>
<p>In the second call, we call <code>foo</code> with a different argument, thus <code>x</code> inside of <code>bar</code> receives a different value, and once the call to <code>bar</code> is made, this is reflected in the return value.</p>
<p>Well, that was easy. And to think I had to wait so long to clarify such a simple idiom. So what is all the noise about anyway? Think of it as a way to split up the assignment of variables. Suppose you don&#8217;t want to assign <code>x</code> and <code>y</code> at the same time, because <code>y</code> is a &#8220;more dynamic&#8221; variable whose value will be determined later. Meanwhile, <code>x</code> is a variable you can assign early, because you know it&#8217;s not going to need to be changed.</p>
<p>So each time you call <code>foo</code>, you get a version of <code>bar</code> that has a value of <code>x</code> already set. In fact, from this point on, for as long as you use this version of <code>bar</code>, you can think of <code>x</code> as a constant that has the value that it was assigned when <code>foo</code> was called. You can now give this version of <code>bar</code> to someone and they can use it by passing in any value for <code>y</code> that they want. But <code>x</code> is already determined and can&#8217;t be changed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.matusiak.eu/numerodix/blog/index.php/2008/04/20/what-the-heck-is-a-closure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
