First-class Functions

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.

First-class boarding, now available!

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:

  • You must be able to be stored;
  • You must be able to be passed as a parameter to a subroutine (function);
  • You must be returnable by a subroutine;
  • You must be able to be created at runtime (during the actual execution of your program);
  • You must have an intrinsic identity (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.?).

If you are able to provide these guarantees, then you are considered a first-class citizen in programming parlance. All common variables in Lua, i.e. number, string, and table, are first-class citizens. Obviously, a number is stored as a variable, can be passed as an argument to a function, and can be returned from a function.

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 points to the function, rather than the function itself). In Java (until Java 8 comes out), I cannot store a function inside a variable.

Lua, and many other scripting languages, elevate functions to first-class citizen status. This means that anything I could do with a number, I can do with a function.

Storing a function in a variable

In Lua, we often create functions like this:

  local function foo(a)
    print(a)
  end

Turns out, when Lua interprets the code, it is kind of, but not exactly, looking at it like this:

  local foo = function (a)
    print(a)
  end

I can even re-assign foo to now be a new function.

  local foo = function(a)
    print(a)
  end

  foo = function(a, b)
    print(a, b)
  end

Passing a function as a parameter

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.

  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, ' '))

This map function is a powerful and widely used function in functional programming languages like Haskell, so much so that it is built into its core library.

Returning a function from another function

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.

  function add(n)
    return function (m)
      return m + n
    end
  end

  local addThree = add(3)
  print(addThree(5)) -- 8

Closuring us out

The first two examples are pretty straight-forward. The adder factory function is a bit weirder if you really pay attention to it. Try tracing the execution path, keeping in mind how scope works:

  1. Lua identifies the function add and the variable addThree.
  2. Lua calls the right-hand side of the assignment statement, add(3).
  3. Lua creates a new, anonymous function that takes in a argument m, returning the expression m + n, and returns the anonymous function from add.
  4. Lua calls print(addThree(5)), which calls addThree(5), which returns 8.

But why does it return 8? Once I have left add, the value of n (in our case 3) is out of scope. Furthermore, it looks like I have no guarantees that if I call add(4), that addThree(5) will not suddenly give me 9.

What Lua and other languages that have first-class functions do is create something know as a closure, which takes a snapshot of the variables that are not within the enclosing functions immediate local scope (i.e. the value of n in our example), and carries that state with it for later use. So, the value of n when I created addThree will, within addThree, will always and forever remain 3.

Comments

Roland_Y's picture

That is awesome post, I just went straight through it.

A suggestion, though, in the part "storing a function in a variable", maybe you can add some lines about the fact that functions are first-class values (in Lua) makes it easy to use them as anonymously. As in:

<pre class="brush: lua">
  print((function(n) return n*n end)(3)) --> 3
  print(6 + (function(n) return n*2 end)(2)) --> 10
</pre>
 
Also, to assess the fact that when functions are treated as reference, when passing them, you can can use that little snippet, as an example:
 
<pre class="brush: lua">
  local function sqr = function(k) return k*k end--> 3
  local foo = sqr
  assert(foo==sqr, 'Assertion failed!')
  print(foo, sqr)

</pre>

Just some random thoughts that came accross my mind. Excellent post, though.
Looking forward the second part about Entity Manager class.
MarekkPie's picture

I've never found much use for anonymous functions in that manner, Roland, so it just slipped my mind that they  can be used in that way.

As far as functions being reference copies, since they share that trait with tables, and since that is not a requirement to be considered a first-class function, I omitted that.

Thanks for the comment.

adminpool's picture

It is a multi-cuisine restaurant serving dishes from Continental, Chinese and Indian cuisines. The famous dish of this restaurant is chow mein served with Chinese gravy chicken or vegetable. This restaurant is located inside the famous Hotel Coorg International, which is an essential part of Coorg Tourism, and this is one of the reasons for its popularity. http://www.multitourist.com/

Paskun's picture

Surprisingly, when i get the chance to hook up with this article i didnt hesitate to get the chance of reading, then it was really surprising information i learned from hear it was really fun and amazing to have this post foredi obat tahan lama dr boyke.

adminpool's picture

It is a multi-cuisine restaurant serving dishes from Continental, Chinese and Indian cuisines. The famous dish of this restaurant is chow mein served with Chinese gravy chicken or vegetable. This restaurant is located inside the famous Hotel Coorg International, which is an essential part of Coorg Tourism, and this is one of the reasons for its popularity. www.multitourist.com

mdello's picture

This site is really great it is very useful and there are alot of usable messages came from the active registered users who make a comment everyday. Thanks for your effort.

buy twitter followers

adminpool's picture

This part covers in-patient hospital services, skilled nursing care, home and hospice care. If you had paid Medicare taxes during your employment, you will not need to pay the premium. But you will be required to pay co-insurance and deductible charges. www.medicarehealthassess.com

iloveyoucham143's picture


First of all Good day! I would just like to give thanks to the admin who posted this one I really appreciate it thank you. 
Yeah right I totally agree with you!  Keep up the good work and Godbless! Anyway I am here to promote real low cost likes in instagram. Guys we are real and legit.
Be with us to, buy low cost instagram likes

 

advardjohn's picture
Property is varied in Lincoln subsequently Park -- both if you're looking to purchase or searching seeking accommodations property. Purchasers seek cost and contemporary features, together with parking areas, rooftop landscapes, and pools. Renters discover affordability within studio flats which begin in the $700 variety.http://www.parkpenny.com/
adminpool's picture

People sometimes get injured in hotels. As such, you need to make sure you get the appropriate insurance for your hotel. You need to make sure you insure the hotel itself and any additional property owned by the hotel.   In addition to property insurance, you will need liability insurance for customer and workers compensation insurance for employees. www.hotelinsuranceplans.com

july's picture

Surprisingly,  when i get the chance to hook up with this article i didnt hesitate to get the chance of reading, then it was really surprising information i learned from hear it was really fun and amazing to have this post. where to buy twitter followers

adminpool's picture

In the property market, the primary market is the initial transaction between the developer and the buyer. This is the only time that the developer gets money from the property. Even if property prices rise by 50%, the developer once they've sold the property doesn't benefit unless they develop and issue more units or buildings. www.fallmoney.com

cloudgenius's picture

A good blog always-comes up with new and exciting information while reading.

Want to   gain twitter favorites .? just  "Visit us"

Your blog provided us with valuable information to work with.Each and every tips of your post are awesome.Thanks a lot for sharing.

 

adminpool's picture

For the students from countries who come for educational purposes there are a number of special policies available in Arizona that is provided by the universities only. In case the particular university that a student is going to does not offer a proper policy in that case the advisor will also be able to make viable suggestions and even refer the student to a good insurance company or broker who may come in handy. www.activeinsuranceadvisors.com

StickyK3ys32's picture

Thanks for sharing this article it can be very useful and helpful to me, so nice to be here it's such a great experienced. I will keep on visiting your website for updates. Once again thank you and keep up the good work. 

purchase soundcloud followers

rysean's picture

GOOD DAY! This is really great article! Full of interesting content.I like what you have written is really good.Thank you for sharing this to us. Keep on posting for more updates.

be with us here <a href="http://organicplays.com/buy-soundcloud-followers/">purchase soundcloud followers</a>

 

akenkenz789's picture

Hey, Good Day! I find your blog a very useful and helpful to someone who wants to learn more in programming or someone who took up programming. In my part, i find it difficult copping up with this. Thanks for sharing. Keep posting and God bless. <a href="http://socialsoundcloud.org/buy-soundcloud-followers/">purchase soundcloud followers</a>

yogesh's picture

Wonderful Content I enjoy This particular kind regards Created for unveiling this excellent.   kamineinsätze

akenkenz789's picture

Hey, Good Day! I find your blog a very useful and helpful to someone who wants to learn more in programming or someone who took up programming. In my part, i find it difficult copping up with this. Thanks for sharing. Keep posting and God bless. <a href="http://socialsoundcloud.org/buy-soundcloud-followers/">purchase soundcloud followers</a>http://<a href="http://socialsoundcloud.org/buy-soundcloud-followers/">purchase soundcloud followers</a>

ram14's picture

The idea is to focus on facts and try and define a baseline problem to share.
Apple authorized service center Kolkata
Macbook pro Dealer in Kolkata
ipad Dealer in Guwahati

ram14's picture

Guar protein offer a wide selection of products for your specific requirements. Established in the year 2008, we are one of the leading Manufacturer, Exporter and Supplier of Compound Guar Protein Meal Feeds and Poultry Feeds.
Guar Meal churi
Roasted korma
Guar korma exporter

Bhoom Ph4nes's picture

This article is such a nice and interesting one, I'm very satisfied with the provided contents. I hope more excellent articles would be posted in your website. Thank you so much and keep sharing.

Be with us to, buy real twitter followers

yogesh's picture

You will be giving a very amazing, efficient & helpful blogposts. ideal would like meant for shairng!  poweredessays

skywrath's picture

A good blog always-comes up with new and exciting information while reading.Your blog provided us with valuable information to work with.Each and every tips of your post are awesome.Thanks a lot for sharing.

Here gain targeted twitter followers.

 

ment's picture

Glad for sharing this wonderful information with us. I like this topic and it reminds me an old something old. I appreciate the entire crew behind this and I wish you the very best for this. Keep posting more updates regarding this in your blog. buy real twitter followers

 

yogesh's picture

Absolute best wishes a great deal while searching for utilizing spending money on such a more than likely possibility to consider such a, Your staff members is defined as fervently using that lots of in conjunction with My partner and i prefer understading for the decided on fashion specific assemble extendable.  aluguel de escavadeira com rompedor

breed's picture

Thanks for forwarding this very important messages we really welcomed your efforts. glad to know this informations surely it will help us more in our onoing projects. purchase twitter followers

yogesh's picture

Providing special special self-discipline factors merely entirely won't generally merely generally know-how risk-free sheltering outstanding some type of attain these kinds of set up reality additionally! how to invest in bitcoin

strobin's picture

At the same time, so few Löve projects use shaders - and I want to contribute to changing that. goat milk soap

yogesh's picture

Some type about remarkably brand-new usually imagine dissertation, an total brand-new a range of private hiring acquire which great rewards presented advises method regularly consistently create along with suggests strategy persistently regularly create along with apart from add-on so that you can shield any person disparities regarding ample or maybe more people, web-sites, together along with simply generally replies.   electrocardiografos

yogesh's picture

Most of the time Many of us don’t help make testimonails due to people online, nevertheless I have to show whereby particulars really crucial many people in order to make this transpire. Basically outstanding mail out!   cheap mri los angeles

ram14's picture

Artemis Hospital, spread across 9 acres, is a 350 bed, state-of-the-art multi-speciality hospital located at Gurgaon, in the Capital Region, India. Artemis Hospital is the first JCI and NABH accredited hospital in Gurgaon.
Hospital in gurgaon
Kidney treatments in gurgaon
Organ transplant in gurgaon

loony's picture

Thanks for accommodating my comments its been a pleasure to visit your place, looking for great news to read from your wonderful source of good information.  Thanks for sharing your remarkable blogs. Best wishes and god bless. purchase twitter followers

SophiaWilliam's picture

great to be here 

 

yogesh's picture

Beyond the simplest of posers, a bill wishs unevens in succession to emporium, manage, further hold quantity essential cherish.  powered essays