From the 3 explanations (Conner,Assumpcao,Mouse) I
have seen so far
in this discussion, a "closure" appears to be the
functional-programming terminology/equivalent for what in OOP would
be an "instance of an object".
In simple cases, yes. But things can get more complex. For example,
it's entirely possible to have two closures and three bindings, with
one binding appearing in both closures, with the value shared between
them:
(let ((c nil))
(list (let ((n 1))
#'(lambda (x)
(princ "setter call #") (princ n) (terpri)
(incf n)
(setq c x)
nil))
(let ((n 1))
#'(lambda (x)
(princ "getter call #") (princ n) (terpri)
(incf n)
c))))
This returns (a list containing) a setter function and a getter
function which set and get the value associated with c in the binding
established by the outer let; there is one binding, which is shared
between the two closures. Each closure also has its own private
binding of n, which is used to provide the "number of times called"
printouts.
This could be done in an OO paradigm, of course, either as two methods
on a single class (with different instance variables for the two call
counters) or as a construct assembled from multiple classes. There is
little-to-nothing that closures permit that can't be done otherwise;
it's just a question of convenience - of how closely the code mirrors
what's in the programmer's mind, if you will.
The only difference I see is in the case of the
closure the
code/method does not have an external name to denote it as there is
only one code-block/method for the closure.
Well, it does not necessarily have any name. In the Lisp examples I've
been giving, the functions have been anonymous lambda expressions, but
they do not have to be. I don't know many closure-supporting
languages, but it's conceivable that there may even be some that
_require_ the code in a closure to have a name.
So is this (closure vs. object-instance) just
different worlds with
different syntax and terminology?
To some extent. I think the two paradigms emphasize different
directions and thus are flexible in different ways; I'd say that
thinking of an instance of an OO class as a closure is looking at it
from a procedural, not OO, point of view (not
necessarily a bad thing);
conversely, looking on a closure as an instance of an
anonymous class
is emphasizing the data rather than the code (again, this may or may
not be a useful way to think of it).
That is, leaving aside the functional-programming vs.
procedural-programming world differences is there something else to
significantly distinguish a closure from an object-instance?
Well...maybe not if your class/instance mechanisms allow you to create
anonymous object classes at run-time and instantiate them on the spot,
though I'd have to think about it more to be sure that's fair.
/~\ The ASCII Mouse
\ / Ribbon Campaign
X Against HTML mouse at
rodents-montreal.org
/ \ Email! 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B