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 15:04

With closures, high order procedures can be used to create objects with their own changeable state and identity.

(define ((person name age sex) msg)
  (cond ((eq? msg 'speak)
         (list "hello, my name is" name "and I'm a" age sex))
        ((eq? msg 'birthday)
         (set! age (+ age 1))
         (list "yay! it's my mother fucking birthday and I'm"
                        age
                        "mother fucking years old! fuck yeah!"))
        (else (list "I don't understand your command"))))


]=> (define boy (person 'Joe 19 'male))
boy
]=> (define girl (person 'Jane 21 'trap))
girl
]=> (boy 'speak)
(hello, my name is Joe and I'm a 19 male)
]=> (girl 'speak)
(hello, my name is Jane and I'm a 21 trap)
]=> (boy 'birthday)
(yay! it's my mother fucking birthday and I'm 20 mother fucking years old! fuck yeah!)
]=> (boy 'speak)
(hello, my name is Joe and I'm a 20 male)
]=> (girl 'speak)
(hello, my name is Jane and I'm a 21 trap)


Read SICP.

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