From sfalcon at fhcrc.org  Thu Dec 14 01:28:32 2006
From: sfalcon at fhcrc.org (Seth Falcon)
Date: Wed, 13 Dec 2006 16:28:32 -0800
Subject: [Rd] caching frequently used values
In-Reply-To: <20061213231840.GA13160@pu100877.student.princeton.edu> (Tamas K.
	Papp's message of "Wed, 13 Dec 2006 18:18:40 -0500")
References: <20061213211729.GA9737@pu100877.student.princeton.edu>
	<45807694.9060707@fhcrc.org>
	<20061213225632.GA12440@pu100877.student.princeton.edu>
	<4580874A.3000108@fhcrc.org>
	<20061213231840.GA13160@pu100877.student.princeton.edu>
Message-ID: <m2y7pbnwwf.fsf@ziti.local>

Tamas K Papp <tpapp at princeton.edu> writes:

> On Wed, Dec 13, 2006 at 03:05:46PM -0800, Robert Gentleman wrote:
>
>> e1 = new.env(hash=TRUE)
>> 
>> e1[["1"]] = whateveryouwant
>> 
>> ie. just transform to characters, but I don't see why you want to do 
>> that - surely there are more informative names to be used -
>
> Because they are derivatives, and best indexed by numbers.  I wrote an
> example to demonstrate what I think the solution is (for memoizing
> powers of numbers).  It works, but I am not an experienced programmer:
> can you please look at it to check that I do things right and do not
> abuse any feature of R?
>
> ## memoize powers of integers
>
> createpowerlist <- function(n) {
>   list(n=n,env=new.env(hash=TRUE))

I would do:
  new.env(hash=TRUE, parent=emptyenv())


> }
>
> getpower <- function(powerlist,i) {
>   iname <- as.character(i)
>   if (exists(iname,powerlist$env))
>     get(iname,powerlist$env)
>   else {
>     res <- i^powerlist$n                # result
>     assign(iname,res,powerlist$env)
>     res

That's fine, but you could do:

  get(iname, powerlist$env) ==> powerlist$env[[iname]]

  assing(iname, res, powerlist$env) ==> powerlist$env[[iname]] <- res

Perhaps that's easier to read since is familiar to those who have used
lists?



[Rd] caching frequently used values
Seth Falcon