Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

closures

Name: Anonymous 2011-11-07 17:48

this thread is dedicated to javascript's most important innovation: the concept of functions that capture their lexical environment

Name: Anonymous 2011-11-07 21:44


var arr = [];
for (var i = 0; i < 10; i++ ) {
  arr[i] = (function (i) {
    return function () {
      return i;
    };
  })(i)
}

beautiful!

i'd like to see your language do the same thing more elegantly!

Name: Anonymous 2011-11-09 1:31

>>1
They're hardly the first to invent closures.
>>6
(loop for i from 0 to 10 collect (let ((a i)) #'(lambda () a))) (Would have been (loop for i from 0 to 10 collect #'(lambda () i)), if not for how loop's bindings work)
Alternatively:
(mapcar #'(lambda (i) (lambda () i)) (loop for i from 1 to 10 collect i))
or

(defun seq (a b) (loop for i from a to b collect i))
(mapcar #'(lambda (i) (lambda () i)) (seq 1 10))

Do you want an array instead of a list? just change 2 atoms: (map 'vector #'(lambda (i) (lambda () i)) (seq 1 10))

Much more elegant, don't you agree?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List