What is the difference between a Function Template and a Delegate? - c#

I have arrived at a point in my self-taught studies where I am not fully grasping what a delegate in C# is useful for. Additionally, on a whim, I decided to take a look at an intro to C++ site and I came across function templates.
Maybe I'm comparing apples and oranges here, but I understood a delegate to be a sort of template for a function that would be defined at run-time. Is this true? If so, how does that differ from a function template in C++?
Is it possible to see (realistic) examples of each in use?

A delegate is a way of taking a member function of some object, and creating a...thing that can be called independently.
In other words, if you have some object A, with some member function F, that you'd normally call as something like: A.F(1);, a delegate is a single entity that you can (for example) pass as a parameter, that acts as a proxy for that object/member function, so when the delegate is invoked, it's equivalent to invoking that member function of that object.
It's a way of taking existing code, and...packaging it to make it easier to use in a fairly specific way (though I feel obliged to add, that 'way' is quite versatile so delegates can be extremely useful).
A C++ function template is a way of generating functions. It specifies some set of actions to take, but does not specify the specific type of object on which those actions will happen. The specification is at a syntactic level, so (for example) I can specify adding two things together to get a third item that's their sum. If I apply that to numbers, it sums like you'd expect. If I do the same with strings, it'll typically concatenate the strings. This is because (syntactically) the template just specifies something like a+b, but + is defined to do addition of numbers, and concatenation of strings.
Looked at slightly differently, a function template just specifies the skeleton for some code. The rest of that code's body is "filled in" based on the type, when you instantiate the template over some specific type.

In C++ terms a C# delegate combines an object pointer and a member function pointer into one callable entity, which calls the member function on the pointed to object.
You can do about the same with std::bind and std::function.
Before C++11 there was a short flurry of articles on how to do very efficient delegates in C++. std::function is a very reasonable compromise and may even attain those levels of efficiency.
Example:
#include <iostream>
#include <functional>
using namespace std;
// Here `function<void()>` serves as a "delegate" type.
void callback_on( function<void()> const f )
{
f();
}
struct S
{
int x;
void foo() const { cout << x << endl; }
};
int main()
{
S o = {42};
callback_on( bind( &S::foo, &o ) );
}

Related

C++ equivalent syntax for a C# generic delegate, and usage with lambdas

In C# I can do this:
delegate void myFunctionDelegate<T>(T arg);
In C++, I understand that I need to use an alias to a template for a function pointer, but the syntax is so bizaare that all of the examples I find just confuse me more.
The following is wrong; how can I correct it?
template<typename T>
using myFunctionDelegate = void (*)(T arg);
I want to use it like so:
template<class T> class Foo
{
...
void someOtherFunction(myFunctionDelegate callback)
{
...
callback(someValue);
}
}
and then:
myClassInstance.someOtherFunction([&](T arg) {
// do something with the callback argument
});
What you have almost works syntactically; the use of myFunctionDelegate simply needs a type argument:
void someOtherFunction(myFunctionDelegate<T> callback)
^^^
And the alias parameter names are optional if you aren't getting any particular benefit from them:
template<typename T>
using myFunctionDelegate = void(*)(T);
However, there is a larger problem: function pointers don't handle state. The lambda used in your sample call uses state by the capturing it does. Thus, a capturing lambda cannot be converted to a function pointer. When it's so handy to pass in such a lambda, function arguments should support that.
There are two common ways of doing so. The first is to forget about forcing a specific return and parameter type. Instead, let the caller pass any object (lambda, function pointer, functor, the result of std::bind) that can be called the way your function calls it:
template<typename Callable>
void someOtherFunction(Callable callback) {
...
callback(someValue);
}
If the call doesn't work, the code will fail to compile1 (with an error that unfortunately isn't too helpful, but the future Concepts additions can easily help there).
On the other hand, you might want to explicitly specify the function type. C++ has a general-purpose type to store any callable object (see the above list). That type is std::function. It's a bit more heavyweight than a simple template parameter, but useful when you need it.
template<typename T>
using myFunctionDelegate = std::function<void(T)>;
void someOtherFunction(const myFunctionDelegate<T> &callback) {...}
[1]: This isn't always true (see SFINAE), but it probably will be as far as you're concerned.
std::function<void(T)> myFunctionDelegate is the (very) rough equivalent of delegate void myFunctionDelegate<T>(T arg)
std::function<void(T)> follows value semantics (it behaves more like an int than a C# object reference) which makes things different.
A lambda closure ([](T t){/*code*/}) whose lifetime (or copies of it) outlives the local scope should not use & based capture. Instead use = based capture (which may require extra work). If the code you are calling does not store a copy of the delegate beyond the lifetime of the call, [&] is optimal. In C++ the lifetime of data is something you need concern yourself with.
This is not intended as a full tutorial on how lambdas and std::function work, but just to point you in the right direction.

C++: Syntax for map where Data type is function?

In C#, what I want would look something like this:
IDictionary<string, action()> dict = new Dictionary<string, action()>();
How do I do this in C++? This gives compiler errors:
map<string, void()> exercises;
Use boost::function, a polymorphous wrapper for any object that can be called with your signature (including functions, function objects etc).
map<string, function<void()>> ...;
Note that the new C++ standard has already included function in <functional>.
To explain the backgrounds: The only builtin mechanism of this kind in C++ are old C-style function pointers (void (*)()). These are extremely low-level, basically just storing the memory address of a function, and therefore far from even coming close to the power of C#'s delegates.
You can't create anonymous functions, neither can you refer to a particular object's member functions or any variables or data (closures).
Thus, one often utilizes so called functors which are classes that mimic the behaviour of a function by overloading the operator (). In combination with templates, they are used whereever ordinary function pointers can be used.
The problem is that these functors often consist of peculiar or anonymous types that can't be referred to conveniently.
The function is the coolest way to address them all - Everything that behaves like a function, including cool new lambda-style expressions.
function<void()> f = []() { cout << "Hello, World"> };
f();
In C++ function pointers need to be used. Using your C++ example, you could inline it as:
map<string, void(*)()> exercises;
But it may be more useful to the casual observer to do it in two lines:
typedef void (*pointer_to_void_function)();
map<string, pointer_to_void_function> exercises;
(Choose names to suit.)
Note, that it's probably even easier to casual observers to add another typedef...
typedef void (*pointer_to_void_function)();
typedef map<string, pointer_to_void_function> ExerciseMapping;
ExerciseMapping exercises;
Then, when you want to use iterators or whatever, you just type ExerciseMapping::iterator instead of needing to type the map... stuff. (This also makes it easier to change your implementation later.)
Try using a function object. For example, you can use boost::function.

are there function pointers in c#?

I am trying to learn some c# coding and wondering if the c++ concept of function pointers is included in c#. I see there are such things as delegates. Are they the same concept? or do they differ on a more fundamental level?
As others have said, you'll want to use delegates for situations in C# that you would have used function pointers for in C++. Delegates are conceptually similar to function pointers but far more pleasant to use, since they encapsulate not just the function, but also the "receiving" object which will be the "this" of the invocation.
Note that the CLR does have the concept of function pointers. If you were to take a close look at how the C# compiler generates code that constructs delegates, you'd see that it makes a managed reference to a function and passes that to a delegate constructor. There is no language feature in C# that allows you to get at the "naked" function pointer and manipulate it directly.
However, since the concept does exist in the CLR, it is theoretically possible that a future version of C# could support function pointers as a first-class concept in unsafe code, just as we support data pointers in unsafe code. What we would do in that case is (1) track the signature of the function pointer as the pointer type, and (2) emit code that uses the "calli" (call through pointer indirection) CIL opcode.
This would increase efficiency in certain obscure interop scenarios where today basically you have to make the marshalling code jump through a lot of hoops, building up delegate instances solely so that the marshaller can get at the function pointer stored in them. If we could avoid requiring the expense of delegate construction and go straight to the function pointer then those now-rare interop scenarios could become less expensive.
However, I wouldn't hold my breath waiting for that feature if I were you. We've prototyped it and it works reasonably well, but I don't think the demand is there to warrant adding it to a general-purpose language like C# at this time.
Delegates are essentially function pointers, but with extra multicast capabilities built in. So you can assign several functions to the same delegate, and they will all be called in sequence when the delegate is called.
Delegates also have built-in asynchronous interfaces, and have co/contra variance when assigning new functions to a delegate (and, in .NET 4, when passing delegates around)
Not in the classical C/C++ sense, no. But the concept is somewhat similar - .NET introduces the concept of delegates to handle situations where you need a variable to invoke a method upon. Delegates cannot be "twiddled" with as pointers can and there is type safety built-in.
If you use C-style function pointers "correctly" the concepts are similar. But there seems to be a lot of legacy code which does funny manipulations of the pointers to skirt around type-safety or what-not.
A delegate is similar to a function pointer in some ways, but actually it is closer to an interface with only one function combined with a way to register handlers and a multicast dispatching mechanism.
So it's a lot more than a function pointer.
C# does have something like a function pointer, which is call delegate. Well... I can't really give you a theoretical answer to the difference between them. But I can give you a difference in code implementation between C# delegate vs C++ function pointers.
C#
delegate void voidFn();
voidFn fnDel;
List<int> intList = new List<int>();
fnDel = intList.Clear
This would compile in c# easily.
C++
typedef void (*voidFn)();
voidFn fnDel;
std::vector<int> intList;
fnDel = intList.clear;
Nope... I am sorry to tell you that in c++ this will not work, even though logically speaking, it felt like the vector's clear function is the same as a void fn(). We don't simply point to an address of the vector's function and say, "Hey! let's clear this vector at this callback" I hope someone can reply a more concrete explanation to this, but I am guessing it got something to do with not knowing which vector to look for.
However, with a little bit of polymorphism... we can transfer something like a C# delegate around...
#include <iostream>
#include <vector>
class A
{
public:
A() {}
virtual void operator()() { std::cout << "A is called"; }
};
class B : A
{
public:
B(std::vector<int>& vec):vec_(vec){}
void operator()() { vec_.clear(); std::cout << "B is called" << std::endl; }
private:
std::vector<int>& vec_;
};
int main()
{
std::vector<int> tmpVec;
for (int i = 0; i < 10; ++i)
{
tmpVec.push_back(i);
}
B* b = new B(tmpVec);
A* a = (A*)b;
std::cout << "Current vec size: " << tmpVec.size() << std::endl;
(*a)();
std::cout << "Current vec size: " << tmpVec.size() << std::endl;
delete b;
return 0;
}
Yup.. that's right... with the help of functors and a little inheritance with their virtual function thingy, we can actually have a form of "delegate void VoidFn()" in Class A. The above code would run class B because of how inheritance work, and will clear 'tmpVec' for us.. So YIPPEE, we can write a pretty flexible C++ callback that doesn't rely on a 'unflexible' function pointer after all!
In addition to the answer of N00bKefka I have to let you know that there are member function pointers in C++ and there is no need to define any new class at all.
Here is how to point at intList.clear, where intList is an instance of std::vector<int>, and then invoke that function without defining any new class at all:
typedef void(std::vector<int>::*voidFn)(); //voidFn is now the type of all pointers to std::vector<int> functions
voidFn fnDel; //fnDel is now an instance of voidFn which was defined above.
std::vector<int> intList; //intList is now an instance of std::vector<int>
fnDel = &std::vector<int>::clear; //fnDel now points at std::vector<int>::clear.
((intList).*(fnDel))(); //Invoking intList.clear through fnDel. A macro can greatly simplify this line of code and make it much more readable.
//But since C++17 you just do
std::invoke(fnDel,intList); //Does exactly the same as the previous instruction.
But of course that C# delegates are the best according to all the other answers here.
Starting from C# 9.0, the answer is yes:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/function-pointers

The Benefits of Using Function Pointers

I have been programming for a few years now and have used function pointers in certain cases. What I would like to know is when is it appropriate or not to use them for performance reasons and I mean in the context of games, not business software.
Function pointers are fast, John Carmack used them to the extent of abuse in the Quake and Doom source code and because he is a genius :)
I would like to use function pointers more but I want to use them where they are most appropriate.
These days what are the best and most practical uses of function pointers in modern c-style languages such as C, C++, C# and Java, etc?
There is nothing especially "fast" about function pointers. They allow you to call a function which is specified at runtime. But you have exactly the same overhead as you'd get from any other function call (plus the additional pointer indirection). Further, since the function to call is determined at runtime, the compiler can typically not inline the function call as it could anywhere else. As such, function pointers may in some cases add up to be significantly slower than a regular function call.
Function pointers have nothing to do with performance, and should never be used to gain performance.
Instead, they are a very slight nod to the functional programming paradigm, in that they allow you to pass a function around as parameter or return value in another function.
A simple example is a generic sorting function. It has to have some way to compare two elements in order to determine how they should be sorted. This could be a function pointer passed to the sort function, and in fact c++'s std::sort() can be used exactly like that. If you ask it to sort sequences of a type that does not define the less than operator, you have to pass in a function pointer it can call to perform the comparison.
And this leads us nicely to a superior alternative. In C++, you're not limited to function pointers. You often use functors instead - that is, classes that overload the operator (), so that they can be "called" as if they were functions. Functors have a couple of big advantages over function pointers:
They offer more flexibility: they're full-fledged classes, with constructor, destructor and member variables. They can maintain state, and they may expose other member functions that the surrounding code can call.
They are faster: unlike function pointers, whose type only encode the signature of the function (a variable of type void (*)(int) may be any function which takes an int and returns void. We can't know which one), a functor's type encodes the precise function that should be called (Since a functor is a class, call it C, we know that the function to call is, and will always be, C::operator()). And this means the compiler can inline the function call. That's the magic that makes the generic std::sort just as fast as your hand-coded sorting function designed specifically for your datatype. The compiler can eliminate all the overhead of calling a user-defined function.
They are safer: There's very little type safety in a function pointer. You have no guarantee that it points to a valid function. It could be NULL. And most of the problems with pointers apply to function pointers as well. They're dangerous and error-prone.
Function pointers (in C) or functors (in C++) or delegates (in C#) all solve the same problem, with different levels of elegance and flexibility: They allow you to treat functions as first-class values, passing them around as you would any other variable. You can pass a function to another function, and it will call your function at specified times (when a timer expires, when the window needs redrawing, or when it needs to compare two elements in your array)
As far as I know (and I could be wrong, because I haven't worked with Java for ages), Java doesn't have a direct equivalent. Instead, you have to create a class, which implements an interface, and defines a function (call it Execute(), for example). And then instead of calling the user-supplied function (in the shape of a function pointer, functor or delegate), you call foo.Execute(). Similar to the C++ implementation in principle, but without the generality of C++ templates, and without the function syntax that allows you to treat function pointers and functors the same way.
So that is where you use function pointers: When more sophisticated alternatives are not available (i.e. you are stuck in C), and you need to pass one function to another. The most common scenario is a callback. You define a function F that you want the system to call when X happens. So you create a function pointer pointing to F, and pass that to the system in question.
So really, forget about John Carmack and don't assume that anything you see in his code will magically make your code better if you copy it. He used function pointers because the games you mention were written in C, where superior alternatives are not available, and not because they are some magical ingredient whose mere existence makes code run faster.
They can be useful if you do not know the functionality supported by your target platform until run-time (e.g. CPU functionality, available memory). The obvious solution is to write functions like this:
int MyFunc()
{
if(SomeFunctionalityCheck())
{
...
}
else
{
...
}
}
If this function is called deep inside of important loops then its probably better to use a function pointer for MyFunc:
int (*MyFunc)() = MyFunc_Default;
int MyFunc_SomeFunctionality()
{
// if(SomeFunctionalityCheck())
..
}
int MyFunc_Default()
{
// else
...
}
int MyFuncInit()
{
if(SomeFunctionalityCheck()) MyFunc = MyFunc_SomeFunctionality;
}
There are other uses of course, like callback functions, executing byte code from memory or for creating an interpreted language.
To execute Intel compatible byte code on Windows, which might be useful for an interpreter. For example, here is an stdcall function returning 42 (0x2A) stored in an array which can be executed:
code = static_cast<unsigned char*>(VirtualAlloc(0, 6, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
// mov eax, 42
code[0] = 0x8b;
code[1] = 0x2a;
code[2] = 0x00;
code[3] = 0x00;
code[4] = 0x00;
// ret
code[5] = 0xc3;
// this line executes the code in the byte array
reinterpret_cast<unsigned int (_stdcall *)()>(code)();
...
VirtualFree(code, 6, MEM_RELEASE);
);
As per my personal experience they can can help you save significant lines of code.
Consider the condition:
switch(sample_var)
{
case 0:
func1(<parameters>);
break;
case 1:
func2(<parameters>);
break;
up to case n:
funcn(<parameters>);
break;
}
where func1() ... funcn() are functions with same prototype.
What we could do is:
Declare an array of function pointers arrFuncPoint containing the addresses of functions
func1() to funcn()
Then the whole switch case would be replaced by
*arrFuncPoint[sample_var];
Any time you use a event handler or delegate in C#, you are effectively using a function pointer.
And no, they are not about speed. Function pointers are about convenience.
Jonathan
Function pointers are used as callbacks in many cases. One use is as a comparison function in sorting algorithms. So if you are trying to compare customized objects, you can provide a function pointer to the comparison function that knows how to handle that data.
That said, I'll provide a quote I got from a former professor of mine:
Treat a new C++ feature like you would treat a loaded automatic weapon in a crowded room: never use it just because it looks nifty. Wait until you understand the consequences, don't get cute, write what you know, and know what you write.
These days what are the best and most practical uses of integers in modern c-style languages?
In the dim, dark ages before C++, there was a common pattern I used in my code which was to define a struct with a set of function pointers that (typically) operated on that struct in some way and provided particular behaviors for it. In C++ terms, I was just building a vtable. The difference was that I could side-effect the struct at runtime to change behaviors of individual objects on the fly as needed. This offers a much richer model of inheritance at the cost of stability and ease of debugging. The greatest cost, however, was that there was exactly one person who could write this code effectively: me.
I used this heavily in a UI framework that let me change the way objects got painted, who was the target of commands, and so on, on the fly - something that very few UIs offered.
Having this process formalized in OO languages is better in every meaningful way.
Just speaking of C#, but function pointers are used all over C#. Delegates and Events (and Lambdas, etc) are all function pointers under the hood, so nearly any C# project is going to be riddled with function pointers. Basically every event handler, near every LINQ query, etc - will be using function pointers.
There are occasions when using function pointers can speed up processing. Simple dispatch tables can be used instead of long switch statements or if-then-else sequences.
Function pointers are a poor man's attempt to be functional. You could even make an argument that having function pointers makes a language functional, since you can write higher order functions with them.
Without closures and easy syntax, they're sorta gross. So you tend to use them far less than desireable. Mainly for "callback" functions.
Sometimes, OO design works around using functions by instead creating a whole interface type to pass in the function needed.
C# has closures, so function pointers (which actually store an object so it's not just a raw function, but typed state too) are vastly more usable there.
Edit
One of the comments said there should be a demonstration of higher order functions with function pointers. Any function taking a callback function is a higher order function. Like, say, EnumWindows:
BOOL EnumWindows(
WNDENUMPROC lpEnumFunc,
LPARAM lParam
);
First parameter is the function to pass in, easy enough. But since there are no closures in C, we get this lovely second parameter: "Specifies an application-defined value to be passed to the callback function." That app-defined value allows you to manually pass around untyped state to compensate for lack of closures.
The .NET framework is also filled with similar designs. For instance, IAsyncResult.AsyncState: "Gets a user-defined object that qualifies or contains information about an asynchronous operation." Since the IAR is all you get on your callback, without closures, you need a way to shove some data into the async op so you can cast it out later.
Function pointers are fast
In what context? Compared to?
It sounds like you just want to use function pointers for the sake of using them. That would be bad.
A pointer to a function is normally used as a callback or event handler.

When to use closure? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen samples of closure from - What is a 'Closure'?
Can anyone provide simple example of when to use closure?
Specifically, scenarios in which closure makes sense?
Lets assume that the language doesn't have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. I am sorry, I do not understand functional languages yet.
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:
string name = // blah
int value = // blah
new Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
Person person = list.Find(x=>x.Age > minAge && x.Region == region);
Again - the alternative would be to write a class with two properties and a method:
internal sealed class PersonFinder
{
public PersonFinder(int minAge, string region)
{
this.minAge = minAge;
this.region = region;
}
private readonly int minAge;
private readonly string region;
public bool IsMatch(Person person)
{
return person.Age > minAge && person.Region == region;
}
}
...
Person person = list.Find(new PersonFinder(minAge,region).IsMatch);
This is fairly comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
for(int i = 0 ; i < 10 ; i++) {
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(i);
});
}
This might not print what you expect, since the variable i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:
for(int i = 0 ; i < 10 ; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(j);
});
}
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures here; or for more detail, see his book C# in Depth, which has an entire chapter on them.
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.
This is somehow reminiscent of:
The venerable master Qc Na was walking
with his student, Anton. Hoping to
prompt the master into a discussion,
Anton said "Master, I have heard that
objects are a very good thing - is
this true?" Qc Na looked pityingly at
his student and replied, "Foolish
pupil - objects are merely a poor
man's closures."
Chastised, Anton took his leave from
his master and returned to his cell,
intent on studying closures. He
carefully read the entire "Lambda: The
Ultimate..." series of papers and its
cousins, and implemented a small
Scheme interpreter with a
closure-based object system. He
learned much, and looked forward to
informing his master of his progress.
On his next walk with Qc Na, Anton
attempted to impress his master by
saying "Master, I have diligently
studied the matter, and now understand
that objects are truly a poor man's
closures." Qc Na responded by hitting
Anton with his stick, saying "When
will you learn? Closures are a poor
man's object." At that moment, Anton
became enlightened.
(http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html)
The most simple example of using closures is in something called currying. Basically, let's assume we have a function f() which, when called with two arguments a and b, adds them together. So, in Python, we have:
def f(a, b):
return a + b
But let's say, for the sake of argument, that we only want to call f() with one argument at a time. So, instead of f(2, 3), we want f(2)(3). This can be done like so:
def f(a):
def g(b): # Function-within-a-function
return a + b # The value of a is present in the scope of g()
return g # f() returns a one-argument function g()
Now, when we call f(2), we get a new function, g(); this new function carries with it variables from the scope of f(), and so it is said to close over those variables, hence the term closure. When we call g(3), the variable a (which is bound by the definition of f) is accessed by g(), returning 2 + 3 => 5
This is useful in several scenarios. For example, if I had a function which accepted a large number of arguments, but only a few of them were useful to me, I could write a generic function like so:
def many_arguments(a, b, c, d, e, f, g, h, i):
return # SOMETHING
def curry(function, **curry_args):
# call is a closure which closes over the environment of curry.
def call(*call_args):
# Call the function with both the curry args and the call args, returning
# the result.
return function(*call_args, **curry_args)
# Return the closure.
return call
useful_function = curry(many_arguments, a=1, b=2, c=3, d=4, e=5, f=6)
useful_function is now a function which only needs 3 arguments, instead of 9. I avoid having to repeat myself, and also have created a generic solution; if I write another many-argument function, I can use the curry tool again.
Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.
For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:
(defun make-adder (how-much)
(lambda (x)
(+ x how-much)))
and use it like this:
cl-user(2): (make-adder 5)
#<Interpreted Closure (:internal make-adder) # #x10009ef272>
cl-user(3): (funcall * 3) ; calls the function you just made with the argument '3'.
8
In a language without closures, you would do something like this:
public class Adder {
private int howMuch;
public Adder(int h) {
howMuch = h;
}
public int doAdd(int x) {
return x + howMuch;
}
}
and then use it like this:
Adder addFive = new Adder(5);
int addedFive = addFive.doAdd(3);
// addedFive is now 8.
The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.
That should explain to you when you would use closures: all the time. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.
One can implement an object system with closures.
Here is an example from Python's standard library, inspect.py. It currently reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object)
This has, as parameters, a convert function and a join function, and recursively walks over lists and tuples. The recursion is implemented using map(), where the first parameter is a function. The code predates the support for closures in Python, so needs two additional default arguments, to pass convert and join into the recursive call. With closures, this reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o: strseq(o, convert, join), object))
else:
return convert(object)
In OO languages, you typically don't use closures too often, as you can use objects to pass state - and bound methods, when your language has them. When Python didn't have closures, people said that Python emulates closures with objects, whereas Lisp emulates objects with closures. As an example from IDLE (ClassBrowser.py):
class ClassBrowser: # shortened
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", self.close)
Here, self.close is a parameter-less callback invoked when Escape is pressed. However, the close implementation does need parameters - namely self, and then self.top, self.node. If Python didn't have bound methods, you could write
class ClassBrowser:
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", lambda:self.close())
Here, the lambda would get "self" not from a parameter, but from the context.
In Lua and Python it's a very natural thing to do when "just coding", because the moment you reference something that's not a parameter, you're making a closure. (so most of these will be quite dull as examples.)
As for a concrete case, imagine an undo/redo system, where the steps are pairs of (undo(), redo()) closures. The more cumbersome ways of doing that might be to either: (a) Make unredoable classes have a special method with universally dorky arguments, or (b) subclass UnReDoOperation umpteen times.
Another concrete example is infinite lists: Instead of working with genericized containers, you frob a function that retrieves the next element. (this is part of the power of iterators.) In this case you can either keep just little bit of state (the next integer, for the list-of-all-nonnegative-integers or similar) or a reference to a position in an actual container. Either way, it's a function that references something that is outside itself. (in the infinite-list case, the state variables must be closure variables, because otherwise they'd be clean for every call)
I'm told there are more uses in haskell, but I've only had the pleasure of using closures in javascript, and in javascript I don't much see the point. My first instinct was to scream "oh no, not again" at what a mess the implementation must be to make closures work.
After I read about how closures were implemented (in javascript anyway), it doesn't seem quite so bad to me now and the implementation seems somewhat elegant, to me at least.
But from that I realized "closure" isn't really the best word to describe the concept. I think it should better be named "flying scope."
As one of the previous answers notes, you often find yourself using them without hardly noticing that you are.
A case in point is that they are very commonly used in setting up UI event handling to gain code reuse while still allowing access to the UI context. Here's an example of how defining an anonymous handler function for a click event creates a closure that includes the button and color parameters of the setColor() function:
function setColor(button, color) {
button.addEventListener("click", function()
{
button.style.backgroundColor = color;
}, false);
}
window.onload = function() {
setColor(document.getElementById("StartButton"), "green");
setColor(document.getElementById("StopButton"), "red");
}
Note: for accuracy it's worth noting that the closure is not actually created until the setColor() function exits.

Categories

Resources