Some guy asserts that the following piece of code is an illustration of closure in Lisp. I'm not familiar with Lisp, but believe he is wrong. I don't see any free variables, it seems to me as an example of ordinary high level functions. Could you please judge...
(defun func (callback)
callback()
)
(defun f1() 1)
(defun f1() 2)
func(f1)
func(f2)
the feeling or act of bringing an unpleasant situation, time, or experience to an end, so that you are able to start new activities: a sense of closure.
The closure property of the whole number states that addition and multiplication of two whole numbers is always a whole number. For example, consider whole numbers 7 and 8, 7 + 8 = 15 and 7 × 8 = 56. Here 15 and 56 are whole numbers as well.
The part of the environment which gives the free variables in an expression their meanings, is the closure. It is called this way, because it turns an open expression into a closed one, by supplying these missing definitions for all of its free variables, so that we could evaluate it.
Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.
There is no function being defined inside func
that would enclose local variables inside func
. Here is a contrived 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 in which the first and last words are enclosed, and which are then reused by calling the newly-created functions f1
and f2
.
This post has several hundred views, therefore if non-schemers are reading this, here is the same silly example in python:
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.'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With