Sonny To on 15 Mar 2010 13:53:45 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: closures


closures can be simulated in C by using malloc to allocate structs on
the heap ... basically simulating an object in the OO sense

On Mon, Mar 15, 2010 at 4:20 PM, Mark M. Hoffman <mhoffman@lightlink.com> wrote:
> Hi all:
>
> I'm trying to refresh/relearn FP skills, most of which I'd quickly forgotten
> after college (and 10+ years of almost all C/asm).
>
> Initially I found closures to be confusing; but now I think that's only because
> the term is thrown around without precision on many of the web pages I happened
> to read about it.
>
> So I'd like to test my understanding with this group...
>
>        int x;
>
>        void foo(int x);
>        void baz(void (*F)(void));
>
>        void callback(void)
>        {
>                foo(x);
>        }
>
>        void bar(void)
>        {
>                baz(&callback);
>        }
>
> C doesn't "support" closures, but the code above has one.  The function pointer
> itself is not the closure... but the binding of foo() w/ the variable x in the
> function callback() is almost it.  I say almost only because a true closure
> would bind foo() to a value as opposed to a variable.
>
>        void foo(int x);
>        void baz(void (*F)(void));
>
>        void bar(void)
>        {
>                baz( &(foo(42)) );      // invalid C code
>        }
>
> The above is a closure, if you could do such a thing in C.  The word closure
> is used here because we create an instance of foo() over which x is "closed".
>
> Do I have it right so far?
>
> I would appreciate it if someone could propose a few problems which are trivial
> to solve with closures, but difficult without.
>
> Thanks & regards,
>
> --
> Mark M. Hoffman
> mhoffman@lightlink.com
>
>


  • References:
    • closures
      • From: "Mark M. Hoffman" <mhoffman@lightlink.com>