[R] Hashes as S4 Classes, or: How to separate environments

From: Hans W Borchers <hwborchers_at_gmail.com>
Date: Sat, 10 May 2008 11:30:27 +0000 (UTC)

For learning purposes mainly I attempted to implement hashes/maps/dictionaries (Python lingua) as S4 classes, see the coding below. I came across some rough S4 edges, but in the end it worked (for one dictionary).

When testing ones sees that the dictionaries D1 and D2 share their environments D1_at_hash and D2_at_hash, though I thought a new and empty environment would be generated each time 'new("Dict")' is called.

QUESTION: How can I separate the environments D1_at_hash and D2_at_hash ?

Reading the articles mentioned in "Tipps and Tricks" didn't help me really. Of course, I will welcome other corrections and improvements as well. Working in R 2.7.0 under Windows.

Hans Werner

#-- Class and method definition for dictionaries -------------------------------


    representation (hash = "environment"),     prototype (hash = new.env(hash=T, parent = emptyenv()))

setMethod("show", signature(object="Dict"),

    definition = function(object) ls(object_at_hash)

setGeneric("hclear", function(object) standardGeneric("hclear")) setMethod("hclear", signature(object="Dict"),

    function(object) rm(list=ls(object_at_hash), envir=object_at_hash)

setGeneric("hput", function(object, key, value) standardGeneric("hput")) setMethod("hput", signature(object="Dict", key="character", value="ANY"),

    function(object, key, value) assign(key, value, envir=object_at_hash)

setGeneric("hget", function(object, key, ...) standardGeneric("hget")) setMethod("hget", signature(object="Dict", key="character"),

    function(object, key) {

        if (exists(key, envir=object_at_hash, inherits = FALSE)) {
            get(key, envir=object_at_hash)
        } else {


# ---- Some tests ----
D1 <- new("Dict")

hput(D1, "a", 1)   # Same as: D1_at_hash$a <- 1
hput(D1, "b", 2)
hget(D1, "a")
hget(D1, "b")

D2 <- new("Dict")

hput(D2, "c", 3)
hput(D2, "d", 4)
hget(D2, "a")      # Wrong: was defined only for D1
hget(D2, "b")

hclear(D2)         # Wrong: clears D1 too

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sat 10 May 2008 - 11:35:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 10 May 2008 - 13:30:38 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive