Skip to content
Prev 359547 / 398502 Next

Persistent state in a function?

Use a local environment to as a place to store state. Update with <<- 
and resolve symbol references through lexical scope E.g.,

     persist <- local({
         last <- NULL                # initialize
         function(value) {
             if (!missing(value))
                 last <<- value      # update with <<-
             last                    # use
         }
     })

and in action

 > persist("foo")
[1] "foo"
 > persist()
[1] "foo"
 > persist("bar")
[1] "bar"
 > persist()
[1] "bar"

A variant is to use a 'factory' function

     factory <- function(init) {
         stopifnot(!missing(init))
         last <- init
         function(value) {
             if (!missing(value))
                 last <<- value
             last
         }
     }

and

 > p1 = factory("foo")
 > p2 = factory("bar")
 > c(p1(), p2())
[1] "foo" "bar"
 > c(p1(), p2("foo"))
[1] "foo" "foo"
 > c(p1(), p2())
[1] "foo" "foo"

The 'bank account' exercise in section 10.7 of RShowDoc("R-intro") 
illustrates this.

Martin
On 03/19/2016 12:45 PM, Boris Steipe wrote:
This email message may contain legally privileged and/or confidential information.  If you are not the intended recipient(s), or the employee or agent responsible for the delivery of this message to the intended recipient(s), you are hereby notified that any disclosure, copying, distribution, or use of this email message is prohibited.  If you have received this message in error, please notify the sender immediately by e-mail and delete this email message from your computer. Thank you.