Advertise with Googlier.comLÖVE • Community Blogs - first-class
http://blogs.love2d.org/blog-terms/first-class
enFirst-class Functions
http://blogs.love2d.org/content/first-class-functions-0
<div class="field field-name-field-blog-term field-type-taxonomy-term-reference field-label-inline clearfix"><h3 class="field-label">Blog Terms: </h3><ul class="links inline"><li class="taxonomy-term-reference-0"><a href="/blog-terms/lua">lua</a></li><li class="taxonomy-term-reference-1"><a href="/blog-terms/functions">functions</a></li><li class="taxonomy-term-reference-2"><a href="/blog-terms/first-class">first-class</a></li><li class="taxonomy-term-reference-3"><a href="/blog-terms/concepts">concepts</a></li></ul></div><div class="field field-name-body field-type-text-with-summary field-label-hidden"><div class="field-items"><div class="field-item even"><p><em>This is part one of a two-part blog post on taking advantage of first-class functions in Lua.
Part one explains the inner workings of first-class functions from both a generic computer science
perspective, and how you implement that within Lua. Part two puts all the theory together to
create a lean version of an Entity Manager.</em></p>
<!--break-->
<h2>First-class boarding, now available!</h2>
<p>Beyond the simplest of problems, a program needs variables in order to store, manipulate, and maintain
some important value. Typically, we think of variables as some number value, or a string of characters.
When dealing with programs of greater complexity, we begin to think about collections of these atomic units
(in Lua, this is accomplished through the monolithic table). Part of being a variable usually requires that
you must have some guarantees:</p>
<ul>
<li>You must be able to be stored;</li>
<li>You must be able to be passed as a parameter to a subroutine <em>(function)</em>;</li>
<li>You must be returnable by a subroutine;</li>
<li>You must be able to be created at runtime <em>(during the actual execution of your program)</em>;</li>
<li>You must have an intrinsic identity <em>(This is a bit harder to understand, but, philosophically,
this means that you have an identity beyond some identifying characteristics. For example,
am I, Michael Kosler, definable beyond my name, age, weight, etc.?)</em>.</li>
</ul>
<p>If you are able to provide these guarantees, then you are considered a
<a href="http://en.wikipedia.org/wiki/First-class_citizen">first-class citizen</a> in programming parlance.
All common variables in Lua, i.e. <code>number</code>, <code>string</code>, and <code>table</code>, are first-class citizens. Obviously,
a <code>number</code> is stored as a variable, can be passed as an argument to a function, and can be returned
from a function.</p>
<p>Functions themselves, however, often did not have this same status. In C, I cannot directly pass a
function as a parameter to another function (I can fake it through a function pointer, but
I am just passing through something that <em>points</em> to the function, rather than the function
itself). In Java <em>(until Java 8 comes out)</em>, I cannot store a function inside a variable.</p>
<p>Lua, and many other scripting languages, elevate functions to first-class citizen status. This means
that anything I could do with a <code>number</code>, I can do with a function.</p>
<h3>Storing a function in a variable</h3>
<p>In Lua, we often create functions like this:</p>
<pre class="brush: lua">
local function foo(a)
print(a)
end
</pre>
<p>Turns out, when Lua interprets the code, it is kind of, <em>but not exactly</em>, looking at it like this:</p>
<pre class="brush: lua">
local foo = function (a)
print(a)
end
</pre>
<p>I can even re-assign <code>foo</code> to now be a new function.</p>
<pre class="brush: lua">
local foo = function(a)
print(a)
end
foo = function(a, b)
print(a, b)
end
</pre>
<h3>Passing a function as a parameter</h3>
<p>Since I can store a function in a variable, I can just as easily pass a function as a parameter.
Suppose I have a table of strings that I want to make all uppercase, print, and then make all lowercase.</p>
<pre class="brush: lua">
local function map(t, f)
for i = 1, #t do
t[i] = f(t[i])
end
end
local text = { 'The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.' }
print(table.concat(text, ' '))
map(text, string.upper)
print(table.concat(text, ' '))
map(text, string.lower)
print(table.concat(text, ' '))
</pre>
<p>This <code>map</code> function is a powerful and widely used function in functional programming languages
like <a href="http://www.haskell.org/haskellwiki/Haskell">Haskell</a>, so much so that it is built into its
core library.</p>
<h3>Returning a function from another function</h3>
<p>Since functions are first-class citizens, I have no problem returning them from other functions.
Suppose I have an adder function, that rather than adding a bunch of numbers together, creates
specialized adder functions.</p>
<pre class="brush: lua">
function add(n)
return function (m)
return m + n
end
end
local addThree = add(3)
print(addThree(5)) -- 8
</pre>
<h2>Closuring us out</h2>
<p>The first two examples are pretty straight-forward. The adder <em>factory</em> function is a bit weirder if
you really pay attention to it. Try tracing the execution path, keeping in mind how
<a href="http://blogs.love2d.org/content/scope-within-lua">scope</a> works:</p>
<ol>
<li>Lua identifies the function <code>add</code> and the variable <code>addThree</code>.</li>
<li>Lua calls the right-hand side of the assignment statement, <code>add(3)</code>.</li>
<li>Lua creates a new, <em>anonymous</em> function that takes in a argument <code>m</code>, returning the expression <code>m + n</code>,
and returns the anonymous function from <code>add</code>.</li>
<li>Lua calls <code>print(addThree(5))</code>, which calls <code>addThree(5)</code>, which returns 8.</li>
</ol>
<p>But why does it return 8? Once I have left <code>add</code>, the value of <code>n</code> (in our case 3) is out of scope.
Furthermore, it looks like I have no guarantees that if I call <code>add(4)</code>, that <code>addThree(5)</code> will not
suddenly give me 9.</p>
<p>What Lua and other languages that have first-class functions do is create something know as a
<a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a>, which takes a snapshot
of the variables that are not within the enclosing functions <em>immediate local scope</em> (i.e. the value
of <code>n</code> in our example), and carries that state with it for later use. So, the value of <code>n</code> when
I created <code>addThree</code> will, within <code>addThree</code>, will always and forever remain 3.</p>
</div></div></div><div class="field field-name-field-addthiswidget field-type-addthis field-label-hidden"><div class="field-items"><div class="field-item even"><div class="addthis_toolbox addthis_default_style addthis_32x32_style " addthis:title="" addthis:url="http://blogs.love2d.org/content/first-class-functions-0"><a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_google_plusone_share"></a>
<a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_facebook"></a>
<a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_hackernews"></a>
<a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_reddit"></a>
<a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_twitter"></a>
<a href="http://www.addthis.com/bookmark.php?v=300" class="addthis_button_"></a>
</div>
</div></div></div>Wed, 20 Mar 2013 23:14:17 +0000MarekkPie25 at http://blogs.love2d.orghttp://blogs.love2d.org/content/first-class-functions-0#comments