Is it closing?

Some guy claims the following code snippet is an illustration of closure in Lisp. I am not familiar with Lisp, but I think that it is wrong. I do not see any free variables, it seems to me as an example of ordinary high-level functions. Could you judge ...

(defun func (callback) callback() ) (defun f1() 1) (defun f1() 2) func(f1) func(f2) 
+4
source share
2 answers

No.

There is no function defined inside func that would include local variables inside func . Here is an example based on yours . Here is a good example:

Input:

 (define f (lambda (first-word last-word) (lambda (middle-word) (string-append first-word middle-word last-word)))) (define f1 (f "The" "cat.")) (define f2 (f "My" "adventure.")) (f1 " black ") (f1 " sneaky ") (f2 " dangerous ") (f2 " dreadful ") 

Output:

 Welcome to DrScheme, version 4.1.3 [3m]. Language: Pretty Big; memory limit: 128 megabytes. "The black cat." "The sneaky cat." "My dangerous adventure." "My dreadful adventure." > 

f defines and returns a closure into which the first and last words are inserted, and which are then reused by calling the newly created functions f1 and f2 .


This post has several hundred views, so if non-schemers read this, here is an equally stupid python example:

 def f(first_word, last_word): """ Function f() returns another function! """ def inner(middle_word): """ Function inner() is the one that really gets called later in our examples that produce output text. Function f() "loads" variables into function inner(). Function inner() is called a closure because it encloses over variables defined outside of the scope in which inner() was defined. """ return ' '.join([first_word, middle_word, last_word]) return inner f1 = f('The', 'cat.') f2 = f('My', 'adventure.') f1('black') Output: 'The black cat.' f1('sneaky') Output: 'The sneaky cat.' f2('dangerous') Output: 'My dangerous adventure.' f2('dreadful') Output: 'My dreadful adventure.' 
+17
source

Here is my contributor as a JavaScript programmer:

A closure is a function that has access to variables defined in its lexical domain (an area that may not be present anymore when the closure is actually called). Here:

 function funktionFactory(context) { // this is the lexical scope of the following anonymous function return function() { // do things with context } } 

As soon as the funktionFactory returns, the lexical region will disappear forever BUT (and this is a big β€œbut”), if the returned function is still referenced (and therefore does not collect garbage), then such a function (closing) can still play with the original context variable. Here:

 var closure = funktionFactory({ name: "foo" }); 

no one except closure can access the name property of the context object (not available for any other object in the software when the funktionFactory returned).

So, to answer your question: is there a func closure? Nope. And callback ? no!

0
source

Source: https://habr.com/ru/post/1346422/


All Articles