Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

What is the Purpose of Closures?

Name: Anonymous 2012-02-29 8:48

I really don't understand what the purpose of closures is. It seems to me that everything that can be written using closures, is just as easily written without. For example:


void main()
{
    int[] haystack = [345,15,457,9,56,123,456];
    int   needle = 123;
    bool needleTest(int n)
    {
        return n == needle;
    }
    printf(find(haystack, &needleTest));
}


Wouldn't this be better written as:


void main()
{
    int[] haystack = [345,15,457,9,56,123,456];
    int   needle = 123;
    foreach(int i : haystack)
    {
        if (i == needle)
        {
            printf(i);
        }
    }
}


Or at least defining the function outside of main() and referencing it inside? I just don't understand the benefit of closures.

Name: Anonymous 2012-02-29 12:10

Closures can be seen as a form of runtime linking. You can create different functions that each have the same code, but refer to different values (for instance functions) that are lexically visible outside of the function body.

Without closures, functions can usually only refer to global variables and functions.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List