Reputation: 1028
I program in Objective-C, I know a bit of Scala, Python and Javascript.
While I'm comfortable with blocks in Obj-C, I would like to know what specific problem do they solve that I couldn't with the earlier versions of the language. Also - are blocks, closures, function literals, named functions, anonymous functions - one and the same thing?
If you can answer with some code examples that would be great.
Upvotes: 1
Views: 660
Reputation:
First of all, in order to answer the question in the title:
Why do we need blocks, function literals, closures in programming languages?
Answer #1: we don't. Brainfuck is Turing-complete without them.
Answer #2: because we're lazy and closures are convenient and easy to use.
What specific problem do they solve?
They solve no specific problem. If you are comfortable with Objective-C, you have surely heard of function pointers, right? Now every time a block is used somewhere, that piece of code could be transformed to an equivalent snippet using a function pointer. The great achievement that closures bring to the programmer is readability. Closures (blocks, lambda functions, etc.) can be (and are) used where they are created, unlike "normal" global functions. Consider the following two pieces of code (two imaginary methods invented with regards to the Cocoa networking APIs):
void url_callback(void *data, size_t length)
{
NSLog(@"Received data %p of size %zu", data, length);
}
[connection sendAsyncRequestWithHandlerFPtr:&url_callback];
versus
[connection sendAsyncRequestWithHandlerLambda:^(void *data, size_t length) {
NSLog(@"Received data %p of size %zu", data, length);
}];
Of course, in the second one it is obvious to whoever reads the code what it does. In the first one, you have to scroll up and down to get to the implementation of the function (if any!) just so you can understand what happens when some data is received.
Are blocks, closures, function literals, named functions, anonymous functions - one and the same thing?
No, they aren't. (Quite.)
Closures and anonymous functions are a mathematical and/or CS theory concept - they descibe subroutines which are first-class values.
Blocks are a particular implementation of closures, as realized by Apple in an extension to the C (and consequentially to the Objective-C) programming language.
Named function expressions are a JavaScript feature that combine the advantages of closures and global functions.
Upvotes: 3