Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Closures in Scheme/Racket?

I am learning Scheme and just came across Closures. The following example provided, demonstrating the use of Closures:

(define (create-closure x)
    (lambda () x))

(define val (create-closure 10))

From what I understand, when the above code is evaluated, val will equal to 10. I realize this is just an example, but I don't understand just how a closure would be helpful. What are the advantages and what would a scenario where such a concept would be needed?

like image 473
DemCodeLines Avatar asked Mar 25 '17 19:03

DemCodeLines


People also ask

What are closures in programming?

A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.

Does racket use dynamic scoping?

Should it be 1, or should it be 2? Racket is statically scoped, and so it decides on bindings before the code runs, which means it must use the x bound to 1. However, in a dynamically scoped language (notably many versions of Lisp before Racket), the most recently bound value of x is used.


Video Answer


2 Answers

val is not 10 but a closure. If you call it like (val) it returns the value of x. x is a closure variable that still exists since it's still in use. A better example is this:

(define (larger-than-predicate n)
  (lambda (v) (> v n )))

(filter (larger-than-predicate 5) '(1 2 3 4 5 6 7 8 9 10))
; ==> (6 7 8 9 10)

So the predicate compares the argument with v which is a variable that still holds 5. In a dynamic bound lisp this is not possible to do because n will not exist when the comparison happens.

Lecical scoping was introduces in Algol and Scheme. JavaScript, PHP amd C# are all algol dialects and have inherited it from there. Scheme was the first lisp to get it and Common Lisp followed. It's actually the most common scoping.

like image 156
Sylwester Avatar answered Nov 22 '22 18:11

Sylwester


From this example you can see that the closure allows the functions local environment to remain accessible after being called.

(define count
   (let ((next 0))
     (lambda ()
       (let ((v next))
         (set! next (+ next 1))
         v))))
(count)
(count) 
(count)
0..1..2
like image 41
Robert Hale Avatar answered Nov 22 '22 16:11

Robert Hale