Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures - differences between R and Javascript

What is the specific difference between R and Javascript that means that in the following two, very similar, examples, I need the additional line in the R version to "fix" the value of the parameter to the first anonymous function?

Is it because R defers evaluation until it's forced (as I think Lisp does), but that Javascript evaluates as early as it can? Or am I on the wrong lines here?

R version

test <- list()
for (i in 1:10) {
  test[[i]] <- (function(index) {
    index <- index # why does R need this line when Javascript doesn't
    return (function() {
      print (index)
    })
  })(i)
}
test[[5]]()
test[[10]]()

Javascript version

test = new Array()
for (var i=1; i<=10; i++) {
  test[i] = (function(index) {
    return function() {
      alert(index)
    }
  })(i)
}
test[5]()
test[10]()
like image 742
SJC Avatar asked Dec 05 '25 05:12

SJC


1 Answers

R uses lazy evaluation. You don't need index <- index
You can use force(index)


In other words, the value of index does not get computed until the value is actually used. Thus if any changes occurred between the time you passed the argument and when you evaluated the argument, those changes will be reflected in the final output.

force, as its name implies, forces the evaluation of an object.

When you use index <- index you are at that moment creating a different object with the same name.

like image 195
Ricardo Saporta Avatar answered Dec 06 '25 18:12

Ricardo Saporta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!