Skip to content

Instantly share code, notes, and snippets.

@richfitz
Created April 21, 2013 22:50
Show Gist options
  • Save richfitz/5431394 to your computer and use it in GitHub Desktop.
Save richfitz/5431394 to your computer and use it in GitHub Desktop.
A somewhat sensible use of <<-
## Captures a variable 'n' in the local scope of the returned
## function. When you run that function it increments the counter and
## prints its current value.
make.counter <- function(start=0) {
n <- start
function() {
n <<- n + 1
message(sprintf("counter value is %d", n))
}
}
f <- make.counter()
g <- make.counter()
f() # 1
f() # 2
g() # 1 -- independent of f
## Better, using S3 classes:
make.counter <- function(start=0) {
n <- start
f <- function() {
n <<- n + 1
}
class(f) <- "counter"
f
}
print.counter <- function(object, ...) {
message(sprintf("Counter value is %d", environment(f)$n))
}
f <- make.counter()
f()
print(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment