My understanding of closures so far is that they combine "open" functions with their surrounding scope, essentially making them closed expressions.
I've seen several examples of how this is implemented in Javascript, most of them using nested functions to create an outer and inner scope and show how the language creates a "snapshot" of the surrounding scope for the inner function.
However, I know there's languages that don't implement closures, for example C. In this particular case, there's also no (native) support for nested functions, so it seems that it is not possible to replicate the "inner" and "outer" cases from JavaScript - and as far as I know, due to this, not having closures doesn't become a important problem.
However, would it be possible for a language to have nested functions and still have no closures? Or does one implies on the another?
The concept of a "closure" is only meaningful when a function can be executed from outside of the scope in which it's declared.
In languages without first-class functions, i.e., where functions can't be passed around or assigned to variables, you could still have nested functions, but they couldn't be used as closures.
Here is the area to play scoping concept in javascript...as you know in java we use class components mostly then we achieve parents functionality's using inheritance but javascript is a weird language...so we can't achieve closures with out nested function
Related
My understanding is that closures are basically functions (and by that I mean piece of code) using variables that are bound to some values.
The partial valuation of a function on the other and is nothing but a new function obtained by another one binding some of its variables/arguments.
It seems o me that two concepts are basically the same: indeed one could regard (i.e. implement) closures as partial valuations of functions, that use additional arguments for the variables to be bound in the closure, and on the other hand a partial valuation seems to be just the closure of a function in which some of its variables-arguments are bound to values.
Is this line of thought correct? Are these two concepts really the same? And if no, what are the differences between these concepts?
Thanks in advance for any answer.
I wouldn't say they are the same thing. They are two concepts that have the same power, but that does not mean they are the same thing.
There's a very narrow semantic difference between the two, and I find myself wondering why both options exist. Are they in any way different functionally, or is one likely just an alias of the other?
There is no difference at all. They are, in fact, the very same method.
To the compiler,
myQueue.async(execute: { foo() })
is exactly the same as
myQueue.async {
foo()
}
When the last argument of any function or method is a function, you can pass that argument as a trailing closure instead of passing it inside the argument list. This is done in order to make higher-order functions such as DispatchQueue.async feel more like part of the language, reduce syntactic overhead and ease the creation of domain-specific languages.
There's documentation on trailing closure syntax here.
And by the way, the idiomatic way to write my first example would be:
myQueue.async(execute: foo)
What you're referring to is called trailing closure syntax. It's a syntactic sugar for making closures easier to work with.
There are many other kinds of syntactic sugar features that pertain to closures, which I cover in my answer here.
As always, I highly recommend the Swift Language guide, which does a great job at explaining the basics like this.
Are there any performance issues with nested functions in F#?
If I have a function which is called on every item in an array, and this function has nested inner functions, does that mean on every iteration it needs to declare, create and assign all the inner nested functions?
Seems awfully inefficient but I really like the readability of nested functions as opposed to private outer functions.
Nested functions are extracted by the compiler into classes that inherit from FSharpFunc, nested within the module or type where their parent function is defined in. So the compiler essentially does for you what you would otherwise do by hand, with outer private functions.
All that happens at runtime is instantiation of these objects. There is a cost to it compared to executing inline code, but I suppose drastically less than what you anticipated in your mental model.
It does leave you with an extra object to GC though. Would this object instantiation matter in a tight loop then? In a naive implementation, where the function object is instantiated anew in each iteration, perhaps yes. But F# compiler is smarter than that and typically instantiates the functions used in the body of the loop once, outside the loop. So again, the cost is probably as low as it can be.
When in serious doubt, consult ILSpy and benchmark. As a rule of thumb - don't fret over it and just use nested functions.
In thinking about blocks, I've always wondered why the
thingers.each { |thing|
example is actually interesting (since there's another, built-in way to do it). In most modern languages there's a way to iterate through a collection and apply some inline code to it. But then I thought that maybe the for (Thing thing : things) { syntax is really a type of block, even in languages like Java-sans-Groovy where there are none.
So the question is: Is a for-each loop a type of block, albeit with a fixed syntax?
Edit: This question is confusing but yet got some attention so I can't delete it. Anyway... by Blocks I mean "closures" and not just code blocks. As far as why I tagged this as language agnostic is that I'm not interested in how a for-each is implemented under-the-hood. I'm more interested in whether, from a programmer's perspective, a for-each could be considered a freebie closure in languages that doesn't have them, like Java.
This is most definitely not language agnostic (as it is tagged).
For example, in Ruby, you are passing a closure or block to the .each method. The semantics are defined by the language.
In C#, foreach compiles to a call to IEnumerable.GetEnumerator and the use of the IEnumerator.MoveNext method. It just depends on the language.
EDIT:
Edit: This question is confusing but yet got some attention so I can't delete it. Anyway... by Blocks I mean "closures" and not just code blocks. As far as why I tagged this as language agnostic is that I'm not interested in how a for-each is implemented under-the-hood. I'm more interested in whether, from a programmer's perspective, a for-each could be considered a freebie closure in languages that doesn't have them, like Java.
No, you are thinking only of one use case for a closure. You can't pass a control structure to a method as you can a closure in some languages. A control structure is not a first class first class data type like a closure is in some languages. In the case of "run this code on each object in a collection" yes, they are semantically similar. However, that it only one example of what you can do with a closure.
You say that you w
As Swangren says, this question is not language agnostic as tagged. Not unless there's some general "IT theory" definition of a "block" that I'm not aware of.
In Java, a "block" is a series of statements enclosed in { }. So a FOR statement normally operates on a block. The purpose of a block is to delimit what is included within certain language constructs, like IF statements and loops.
I believe C and C++ have similar definitions of a "block".
Most languages have a similar concept.
Not sure if this helps.
foreach ($foo as $bar) {
$baz = 'Hello, World!';
}
echo $baz; // 'Hello, World!', "leaked" from the "closure"
Nope, sorry, foreach loops are not lambdas, closures or functions in languages where they aren't explicitly such.
Please elaborate. My definition of a "block" is a section of code that's grouped together. In this case there's a lot of stuff in Java can be a "block"
If you are talking about ruby-style blocks, which are really closures, then Java doesn't support them (not in any sane fashion anyways). foreach is a control structure, and behaves differently from closures.
On your updated question: It's easy to use closures as control structures, but the other way around is harder, if not impossible. A closure is a first class function, which allows you to do some pretty cool stuff with it - not just iterating through elements.
i am kinda confused reading the definition between the two. Can they actually intersect in terms of definition? or am i completely lost? Thanks.
Closures, as the word tends to be used, are just functions (or blocks of code, if you like) that you can treat like a piece of data and pass to other functions, etc. (the "closed" bit is that wherever you eventually call it, it behaves just as it would if you called it where it was originally defined). A monad is (roughly) more like a context in which functions can be chained together sequentially, and controls how data is passed from one function to the next.
They're quite different, although monads will often use closures to capture logic.
Personally I would try to get solid on the definition of closures (essentially a piece of logic which also captures its environment, i.e. local variables etc) before worrying about monads. They can come later :)
There are various questions about closures on Stack Overflow - the best one to help you will depend on what platform you're working on. For instance, there's:
What are closures in .NET?
Function pointers, closures and lambda
Personally I'm only just beginning to "grok" monads (thanks to the book I'm helping out on). One day I'll get round to writing an article about them, when I feel I understand them well enough :)
A "closure" is an object comprising 1) a function, and 2) the values of its free variables where it's constructed.
A "monad" is a class of functions that can be composed in a certain way, i.e. by using associated bind and return higher-order function operators, to produce other functions.
I think monads are a little more complicated than closures because closures are just blocks of code that remember something from the point of their definitions and monads are a construct for "twisting" the usual function composition operation.