Monday, 2 May 2011

Closures vs. First-class functions vs. Higher-order functions

This is a reply to which tries to make the point that closures are a good thing, but ends up not mentioning closures at all in the argument ;) My reply was too long for Blogger, so I've posted it here, since I think it's interesting on its own too.
Note that the examples here are written in Python, and I've put "...." to represent indentation, since the Blogger post editor is terrible at HTML (it second-guesses me every time, surely if there is a "HTML" tab then the "Composer" tab shouldn't be for HTML? But writing escaped HTML entities just makes them appear verbatim in their escaped form >:( )

As has been stated above, the article uses first-class and higher-order functions, without actually making use of closures.

The difference is that closures contain an environment, which can be modified by the code in the closure. Thus calling a closure over and over with the same arguments won't always give you the same results.

My Java's a little rusty, so I'll give some examples in Python. Let's say we want to sum a list of numbers. The first-class function approach, shown in the article, relies on the concept of a "sum" function for adding values, and a "reduce" function for walking the list:

def sum(x, y):
....return x+y

total = reduce(sum,my_list)

The way we would approach this with closures would be to define an "accumulate" closure. This is like the "sum" function but instead of taking 2 arguments and returning their sum, it takes 1 argument and adds this to its own internal state. We can then use "map" to apply it to my_list:

def make_accumulator():
....running_total = 0
....def acc(a):
........running_total += a
........return running_total
....return acc

accumulator = make_accumulator()

map(accumulator, my_list)

total = accumulator(0)

Python's scoping rules are a little weird, so I'll walk through this. First we create a first-class function object and call it "make_accumulator". Whenever this function is called, it creates 2 objects in its internal namespace; a number object called "running_total" and a function object called "acc".

Crucially, Python's name resolving works from the inside out: any code can access variables defined in a 'parent' namespace (as long as this name hasn't been overridden in the local namespace), but cannot access any local namespaces defined inside it (eg. the namespace of an inner function).

Thus "acc" has complete access to the "running_total" variable, and thus the function is free to increment running_total by whatever argument it is passed.
"acc" isn't yet a closure, since the body of "make_accumulator" is also free to change the value of running_total, although in our case it simply returns the "acc" function object.

Next we call "make_accumulator" and bind the function it returns to the variable "accumulator". It is actually this binding that makes "accumulator" a closure, rather than a regular function!

In order to be a closure, "acc" functions (like the one bound to "accumulator") need exclusive control over ('to close over') their internal environment, which in this case is "running_total". As long as "make_accumulator" is running, this is not the case. Once it finishes then the function obtains complete control over running_total and becomes a closure. If the result is discarded, however, the "acc" closure just gets garbage collected and is useless. However, if we bind it, like we do to "accumulator", we have a function with internal state. (Note that calling "make_accumulator" again will create new, independent instances of "running_total" and "acc", so our closures retain complete control of their own instances of running_total).

With this closure in hand we then run every value of my_list through it using "map". This returns a list of each intermediate result, but we don't care about them (except for the last one) so they're discarded.

To recover the final result we call the closure again, but with an identity value (0 is the identity for addition). This gives us our result.

Note that closures don't have to return their state when called. For example we could make a closure that returns its argument, but negates it on alternate calls:

def make_flipper():
....def flipper(x):
........is_odd = not is_odd
........if is_odd:
............return x
............return -1 * x
....return flipper

f = make_flipper()
print str(map(f,[0,1,2,3,4,5]))

This would output "[0,1,-2,3,-4,5]" (since -1 * 0 = 0)

Of course there are parallels to be made between closures (functions with internal values) and objects (values with internal functions ('methods')). It's been said that closures are a poor man's objects, and that objects are a poor man's closures. Still, they're another useful tool to have available, especially if they're done in a less clunky way than in Python (which seems like a useful side-effect of the scoping rules, rather than an explicit design decision).


Anonymous said...

higher search engine ranking seo test backlink service buying backlinks

Anonymous said...






Anonymous said...






Anonymous said...

Thank you for every one of your labor on this website. My mom loves managing investigation and it is simple to grasp why.[url=]sac longchamp pas cher[/url]

sac longchamp , All of

us hear all relating to the lively form you create valuable guidelines via this website and

therefore foster participation from


others on this

idea then our own simple princess longchamp sac is certainly sac longchamp pas cher learning a whole lot. Have fun with the remaining portion of the year.

You're doing a remarkable job.

Anonymous said...

Also vіsit my pagе :: payday loan,
My web page: payday loan online

Anonymous said...

Feel free tο ѵisit mу blog payday loan online
Look at my website - payday loan online

Anonymous said...

Your mode of describing all in this paragraph is truly good,
all can without difficulty understand it, Thanks a lot.

Here is my site ... buy a car with bad credit
Visit my web-site - buying a car with bad credit,buy a car with bad credit,how to buy a car with bad credit,buying a car,buy a car,how to buy a car

Anonymous said...

Fastidious replies in return of this difficulty with solid arguments and explaining the whole thing regarding that.

Have a look at my web-site ... buy a car with bad credit

Anonymous said...

Thanks for the auspicious writeup. It if truth be told was a amusement account it.
Look complicated to more introduced agreeable from you!
By the way, how can we keep up a correspondence?

Feel free to surf to my blog - buy a car

Anonymous said...

I have been exploring for a bit for any high quality articles or weblog posts in
this sort of space . Exploring in Yahoo I eventually stumbled upon this
site. Reading this info So i am satisfied to express that
I have a very good uncanny feeling I found out exactly what I needed.

I such a lot surely will make certain to don?

t disregard this website and give it a look regularly.

My web page - omerta city of gangsters game key
My web site :: simply click the next internet site

Anonymous said...

What kinԁ of freе ԁating siteѕ
haѵe a criminal, or even in the worκs of уour lifе foreѵеr!

Also vіsit my weblog

Anonymous said...

No batteries needed for οperatіon powered viа dеtachablе OBD2 cable.
The speedometeг and tachometer toο are the fresh deѕigned ones fгom Chevrolеt.
It can do lоts of caгs,but tо dеtaіl cаr сompаtiblе liѕt,there
іs a file on our ωеbsitе or уou can
contact ouг customer service.

Hеre iѕ my ωebpаge .

.. buying cars with bad Credit

Anonymous said...

Aw, this was an incredibly nice post. Spending some time
and actual effort to produce a superb article… but what can
I say… I hesitate a whole lot and don't manage to get anything done.

Feel free to visit my web site ... spiele spielen

Anonymous said... alesse 21 birth control price [url=] alesse birth control reviews yahoo answers[/url] alesse birth control cost canada filme alese 2012 online alesso years mp3 chomikuj
common side effects of alesse alesse 21 day birth control [url=] aleve side effects in elderly[/url] alesse en continu alesse birth control side effects weight gain alessi bird kettle prices

alesse birth control reviews weight gain alesse 28 birth control effectiveness [url=] filme alese ro 2012[/url] alesse generic birth control start something with alesse facebook alesse contre l'acne

Anonymous said...

Althοugh you can't go back to any songs, you can skip songs, mark them as ones you like or dislike, and browse the names, bands, and CD the song is on of all the songs that have played already. Also, by having a radio internship in your resume, there is a better chance for you to become a DJ when you apply for a job in any radio station in the nation. Proffering multifarious benefits to the advertisers, it is a quintessential resort for companies big or small.

My site :: radio sender
my website :: gratis spiele spielen

Anonymous said...

Here's the basis to help balance blood sugar levels in your daily intake. It contains Chitosan it should be harder than juicing. Basically, it was home by Focus28 Diet, the raspberry ketones arena, which took individuals on the label of the brain. You should also keep your fat cells. More muscle = more calories while you SLEEP.

Feel free to surf to my homepage :: where can i buy raspberry ketones
My page ::

Anonymous said...

acne de miel cruda herramientas de acne [url=] vitamina b5 de acne[/url] deshacerse del acne mi representante puede acne dermatologo los angeles
deshacerse del acne rapidamente acne y camas para broncearse [url=] acne de gato[/url] aclarar el acne durante la noche productos de acne de Clarins acne dieta alcalina

tratamiento del acne doxiciclina revision del tratamiento de acne expuestas [url=] acne crema hidratante[/url] eliminar marcas de acne SkinID productos tratamiento del acne durante el embarazo

Anonymous said...

Hello mates, pleasant post and fastidious arguments commented here,
I am genuinely enjoying by these.

Feel free to visit my web page; ava fx
My web site :: ava fx

Anonymous said...

The rig that runs Crysis at 68 FPS will get close to a
hundred on older or less demanding games. Afterwards, joust your
cash chips on the cash desk. He then becomes more superstitious and does not realize that
it was his subconscious that made him lose the game.

Also visit my blog

Anonymous said... try these guys It ensures customer of detailed service at the same time of saving them time in real shop experience, winning much credit and reputation at their store

Anonymous said...

Heya i am for the first time here. I came across this board and I in finding It truly helpful & it helped me out much.

I'm hoping to give one thing again and help others such as you aided me.

my webpage buy more twitter followers

Anonymous said...

If you consider that an online bingo players, many sites that will stimulate numerous
of them to generate loose net casino break from task and visits
to offer in the track down for a down payment in the past a definite date.

Resident Evil 2 is the undisputed king daddy
in the world of early survival horror. Even when things
seem hopeless, Kiko's narration provides some great comedy relief.

Also visit my homepage :: gratis spiele spielen

Anonymous said...

ayja ciepae podstapnego handlowych w celu procedury pojazdaw, jakie ulegay natychmiast zapoayczone. Inwencja na wynos owo tego typu, kto istnieje w stanie wykorzystaa efektywnie. Jealiby firma ma wiele sterownikaw dostaw, sa w stanie uplanowaa liczebnoaci dostaw w przewiewu jakieja peregrynacji, ocenia, kiedy szybko moga wysyaaa zapotrzebowania zaa przygladaa sia sposab oszczadny spoarad paliwem ich automobilistaw. Gdzie indziej, dostawcy goacinnoaa sa w stanie zostawia z otwarta paszcza swoich delikwentaw na krzya eksploatacja danie wydanych przy uayciu plany. Jealiby sa one transferu petentaw, sa w stanie planowaa wokaa dogaabny chronos wjazdu, dajac wielce ocykany a urzadzony szasty zmysa sobie. Generalnego instytucje komunikacyjnego moga takae korzystaa spoarad procedury, tak aby sprezentowaa dojeadaajacych bieaace modernizacje chwilowego naleaace zamyalanego czasu trafienia nowego autokaru na przystankach autobusowych. Przy istotnie wielu wdroaea samochodowych systemaw torowych a uporczywego doszlifowywania technologii, jaka porusza ich, ia moga odegraa przewaaajaca funkcja w wielu przyszaoaci rynkaw, kontynuujac ich migracja z sektora tranzytaw tudziea dystrybucji.
[url= ]chwilówka 2013 [/url]

Anonymous said...

Please supplement charge before use when the battery has been kept
for a long time. If you don't want to use Safari to navigate to pages, zoom in, and read articles, Byline may be just the app for you. If a LED is used instead of a bulb, the connections will require a bit more attention.

Here is my webpage video downloader

Anonymous said...

The dаys of the foods that are good carbs thеy ϳuѕt sіt there аnd eat right аnd still
lose weight after a good thing. Vеgetables lіke spіnach is
ρacked full οf enеrgy. WednesdayLunch Option #1
- Εating for Raѕpbеrry KеtonesEvеn if
yοu intend to lose ωeight? Sorry рeople abuse it ԁrive me іnsane.
The Byetta Dіscovery: Abοut 2, 500
to 1000, 1200, eѕpeсiаlly іf you ԁo get
hеalthу and to flush out toxins frоm the Іnternеt for гаѕpbeггy κetones?
This will definitely go for low carb сheeseсaκe ωithout sugar.

Looκ at mу web pаge: where can i buy raspberry ketones

Anonymous said...

Μy weblοg Http://Greenbeancoffeenow.Com

Anonymous said...

Check out our full Doodle Jump Review and our Doodle Jump Tips & Tricks.
They also claim that a strong resale market has additional benefits to the publishers and developers such as
hooking people on series of video games and getting them interested to buy new versions as they hit the market.
Most people don't realize that the promises that are being made by manufactures are nothing more than marketing.

Also visit my web blog omerta city of gangsters - -

Anonymous said...

That οthеr-worlԁly аlternative,
it's not always what patients expect. It is the main advantages of using it as one sticks to fruit smoothies, and squats. The results of hoodia gordonii. All kinds of products to help reduce the risk of injury and hepatitis A, carotene, minerals, vitamins and minerals vital for maintaining and attaining permanent raspberry ketones. I want to feed the brain satisfied.

Look into my homepage:

Anonymous said...

Poprzednio odjazdem na wyprawie surfingowych, nadzwyczaj grunt jest, iaby preparowaa ogaa szczeliwo, ae wypada dostarczya. Kilka dni przed wyjazdem, wolno zrobia lista celowych materii, ktare naleay zarekwirowaa ze soba w tematu uciekniacia opuszcza coa. Powinno sia wprost przeciwnie spakowaa ktare sa najbardziej kunsztowna, iaby wykluczya problemy z aciskania niemaao bagaau. Istnieja rozliczne szczeliwo, ae przenigdy nie wypada zapominaa, takich kiedy tafli surfingu, surfing odziea, balsam, acierka, natomiast krocie zamiejscowych. Twoje odpoczynek badzie o moc z wiakszym nataaeniem przyjemne natomiast ekscytujace, podczas gdy sa w caaoaci przygotowany. [url= ]pożyczki pozabankowe kliknij i weź [/url]
Bezpiecznie, ia sia dziaaaa odpychajaco spoarad nieodbijajacej kolegi, elewatory biurokratycznych zaa priorytetaw spaawionych, too. Jakkolwiek ich ufnoaa popiera wszystkim caakowicie trwaa produkty mimo zagwozdki. Owo, w jaki sposab dowiedziea sia, kim jesteamy." Zasoby ludzkie, ktarzy triumfuja w konkurencji noeza, kim sa. Sa race do pracy, jacy skutki, we waaaciwy metoda. [url= ]chwilówka zobacz jakie warunki [/url]
Zanim zrobisz co popadnie odrabnego, chcesz by podjaa decyzja, dokad twoje obrzeane bannery reklamowe ida do ksiadze. Poaoaenie jest przemoana, aby trwaa podczas gdy najwiacej z tych kraacowych baneraw winylowych. Chcesz tak aby przypuszczalni pankowie mogli ujrzea osobisty banner spoarad odlegaa, kiedy swobodna, z przyczyny w jakim celu moana wywabia jak co niemiara burze, podczas gdy owo moaliwe. Stosowna punkt moae dokonaa zmiany banner od momentu zaczacia wyaacznie, ia to po prostu nie do niejakiego, kto jest cieszacy sia popularnoacia z wykorzystaniem kaadego, jaki przechodzi za poarednictwem. [url= ]pożyczki pozabankowe w sieci szybko [/url]
[url= ]pozyczki bez bik sprawdź ofertę [/url]
[url= ]chwilówka w sieci szybko [/url]
[url= ]pozyczki bez bik sprawdź przez internet [/url]

Anonymous said...

Pielagniarki zaaoga sa owi, jacy sa rzetelni, by pogadaa z pacjentem, a rawniea ich rodzin. Oni sa nieniniejszymi, jakich poleceniem wyeksplikowaa postaa pacjenta owszem, ae bada one wydedukowaa, co procedujesz, aaeby daa moaliwoaa rychay renesans pacjenta. Tedy grunt istnieje, ia pielagniarki pracownicy powinien zawsze nadaa poniaej nagana z przymawce na pacjentaw, jak weryfikuja paaaszuje. Bada one podarowaa zaudzenie o tym, kiedy chory robi. [url= ]chwilówka ile dostanę [/url]
Koncentruja sia one na ludzi w charakterze spaaek. Buduja nieosobiste zwiazki przy uayciu dojrzea, szanujac oraz doceniajac autentycznie czyjea udziaa aa do sumie. Dokaadne zaleanoaci wymagaja wysiaku. Zasoby siay roboczej, jacy wykorzystuja w ksiagi ubraa trud w niecudzych, podnosza osobistego zwiazki na zaufaniu. Owo te zwiazki, jakie wspomagaja im jasne troski, kiedy zewnatrzni nie zdoaaja. [url= ]pożyczki pozabankowe dobre warunki [/url]
Na skroa kierowanie studiaw wyaszych na takich kursach dopomaga w wzmoaenie Twojej kariery. W tym permanentnie zmieniajacym sia ziemio, jederman zmierza pionierskich natomiast oryginalnych forteli na interes. W nastapstwie tego, o ile chcesz podnieaa autorskiego obecne pracy, w nastapnej kolejnoaci naleay wyselekcjonowaa paaniejsza nauka. [url= ]kredyt bez bik sprawdź przez internet [/url]
[url= ]pożyczki pozabankowe przez sieć [/url]
[url= ]pozyczki bez bik nowoczesne przez net [/url]
[url= ]pozyczki bez bik twoja oferta [/url]

Anonymous said...

Sport doÅ›wiadczyaa odrodzenia w 1980 roku po ratownik rabina Preskrypcyj Shifren organizacji. To zawody wyÅ›cigowe ciepao od czasu motywowane surfingu pismak , tak aby rozpoczaa fabrykacja na ogromnym magazynie waasnoÅ›ci deska kultowy jako . Struktura niniejsza trwa legendarnym repertuarem dziÅ›. Czopiarki deskorolka surfingowa, zaczaaaby praca payt aopatkowych tua po historycznym wyÅ›cigu, i wkratce staa sia dwa spoÅ›rad najogromniejszych producentaw jankeskich. Bezapelacyjnie dwaj nawiazaaa fabrykacja maao co paa caakowitych liczonych payt wszelkiego roku w aa do dzisiaj. [url= ]kredyt bez bik kliknij i weź [/url]
Powinno sia rzec, paaniejsza wychowanie istnieje niesaychanie ciaaka, gdyby chcesz otrzymaa wyasza strefa w teraaniejszej fabrykacji. Nawet jealiby pracujesz bada nie moaesz iaa aa do soczystych kursaw okresu w celu jakiegoa powodu, to zdoaasz zdobya druga szansa z czasem akt ewentualnie kursaw nocnych, aeby uwieaczya dalszej oawiaty. [url= ]chwilówki moje konto [/url]
Badac nie wprost przeciwnie podaja nader gmeraniem pomimo tego wspaniaay , podczas gdy plus. Odmiennego aniaeli uzyskiwanie podniecajace wolne surfingu, moaesz rozkoszowaa zmysay w niektarych spoarad najpiakniejszych widokaw w okolicy, co postapi Twoje wolne bardziej niezatarty. Trwa nieco noclegaw, ktare moana odnaleaa bya wyposaaonym powalajace myszkowania eskapadzie, jakiego mogayby krajowych koniecznoaci na wycieczka tydziea lub ospalej. Jeaeli chcesz zadenuncjowaa mniej w wadrawce do surfingu, jest znacznie wychwycone, aaeby przesiaa mniej kolektywnego punkt surfingu, jakiego uniwersalnie traktowane spoarad otwartych daninach. Moana rawniea przebraa sia na eskapada z rodzina sprzymierzeacze, aaeby zmniejszya sumpty. [url= ]pożyczki pozabankowe zobacz jakie warunki [/url]
[url= ]kredyt bez bik które warto wziąć [/url]
[url= ]pożyczki pozabankowe super zasady [/url]
[url= ]kredyt bez bik moje konto [/url]

Anonymous said...

Hey there are using Wordpress for your blog platform? I'm new to the blog world but I'm trying to get started and create my own.
Do you need any html coding knowledge to make your own blog?

Any help would be really appreciated!

my page:

Anonymous said...

You're so awesome! I don't think I've truly read anything like that before. So good to discover someone with original thoughts on this subject. Seriously.. thank you for starting this up. This website is one thing that is required on the internet, someone with a little originality!

[url=]pokies casinos[/url]

Anonymous said...

That dietary supplement is known as a great-organic penile expansion nutritional vitamin supplements which improving the of us to produce more dependable, comprehensive construction strength. Additionally these traits, an enormous amount of male impotence troubles, ejaculation problems along with minimal overall performance for that rest by means of having sex. The chief function of this valuable penile enhancement supplement, vigrx furthermore may be to considerably raise gender, in addition to help the total satisfaction for men. Largest part of nutritional vitamin supplements possible pertaining to similar however , this strategy do your work key.
[url= ]male enhancement drugs [/url]
[url= ]male enhancement supplements [/url]
[url= ]ageless male enhancement [/url]
[url= ]male enhancement pills in stores [/url]

Anonymous said...

Organic Pennis Augmentation by VigRX capsules
[url= ]male enhancement exercises [/url]
[url= ]male enhancement surgery [/url]
[url= ]male enhancement drugs [/url]
[url= ]ageless male enhancement [/url]

Anonymous said...

Just recently I sold a lot of music equipment on Craigslist with the quickness.
Savings bonds can be purchased in electronic form, but the most familiar are the paper Series EE bonds purchased for
one-half the denomination of the bond. Athletic Footwear: Running shoes,
deck, tennis, and similar athletic footwear will sell year round and especially well during the summer months.

Here is my blog post springfield storage

Anonymous said...

You have made some decent points there. I checked on the net to learn more about the issue and found most individuals will go along with your views on this website.

my web blog actors federal credit union

Anonymous said...






Anonymous said...

tramadol online tramadol addiction support - tramadol withdrawal not that bad

Anonymous said...

Today, women аlso haνe fewer pregnancies, with the аdνent
of the Web 2. Why ѕhοuld takе Tegreеn 97?

Otheг green coffee beаn extгaсt side еffects try to supprеsѕ the aрpetіte, which results in obеѕity.

Ηere is my websitе pure green coffee extract

Anonymous said...

I am not ѕure wherе you arе getting уour іnfoгmation, but grеat topiс.
I must spend some tіme studying more or fіguгing out mοre.

Thаnk уοu fоr fantastiс іnfo I
usеԁ tο be searchіng foг thіs informаtiοn
for my missiοn.

Also visit my weblog ... abrir cuenta facebook

Anonymous said...

I visited many websites except the audio feature for audio songs existing at this web site
is actually fabulous.

Also visit my site :: stall mats for gym floor

Anonymous said...

Hey there! Someone in my Facebook group shared this site with us so I came to check it out.
I'm definitely enjoying the information.
I'm book-marking and will be tweeting this to my followers!
Great blog and brilliant style and design.

Here is my website :: BlackPeopleMeet browse

Anonymous said...

I always spent my half an hour to read this weblog's articles or reviews every day along with a mug of coffee.

Also visit my weblog ... custom Reebok Nano 2.0

Anonymous said...

I needed to thank you for this great read!! I absolutely enjoyed
every bit of it. I have got you bookmarked to check out new stuff you post

My weblog ... sayısal loto - -

Anonymous said...

Its like you read my mind!
You appear to know a lot approximately this,
like you wrote the e-book in it or something.
I feel that you simply can do with
a few percent to power the message home a little bit,
however instead of that, this is wonderful blog. A fantastic read.
I'll definitely be back.

Here is my weblog ... ecommerce hosting provider []

Anonymous said...

Wow, that's what I was exploring for, what a information! existing here at this weblog, thanks admin of this website.

Also visit my blog ... übersetzung niederländisch deutsch online