I am fairly new to R and while I was reading the manuals I came across a passage about lexical scoping along with this code example:
open.account <- function(total) {
list(
deposit = function(amount) {
if(amount <= 0)
stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
},
withdraw = function(amount) {
if(amount > total)
stop("You don't have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
},
balance = function() {
cat("Your balance is", total, "\n\n")
}
)
}
ross <- open.account(100)
robert <- open.account(200)
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
So, I understand what the above code does, I guess I'm still confused about exactly how it works. If you can still access a function's "local" variables after the function has finished executing, isn't it very hard or impossible to predict when a variable is no longer needed? In the code above, if it were used as part of a larger program, would "total" be kept stored in memory until the entire program was done?(Essentially becoming a global variable memory-wise) If this is true, wouldn't this cause memory use issues?
I've looked at two other questions on this site: "How is Lexical Scoping implemented?" and "Why are lexical scopes prefered by the compilers?". The answers there went right over my head but it made me wonder: If(as I am guessing) the compiler isn't just making all variables global(memory-wise) and is instead using some technique to predict when certain variables won't be needed anymore and can be deleted, wouldn't doing this work actually make things harder on the compiler rather than easier?
I know that was alot of different questions but any help would be nice, thanks.
total
is a global variable in this instance since you use the<<-
operator, see?"<<-"
. You should be able to inspecttotal
directly in an interactive session. If instead you used<-
it would not be available after the function execution, but it would also break this particular function. – Difficultybigdata
,bigmemory
,ff
,data.table
, etc to get around some of R's design limitations. Other things you can do are store your datasets in a database and only query them when necessary; seeRODBC
,DBI
,RMySQL
,SQLite
and so on. – Ashcan