datastructures icon indicating copy to clipboard operation
datastructures copied to clipboard

Adding has_key() and/or default values to hasmaps

Open vgherard opened this issue 5 years ago • 0 comments

Hi! I just came along this very nice package and was trying to play around a bit with hash tables.

My particular use cases require many queries to keys which may be absent from the table. For a simplified example, suppose I want to build a table of occurrences of elements in a vector v of strings through a single pass over the vector; ideally, I would like to do something like this:

# pseudocode
h <- hashmap("integer")
for (x in v) {
    h[x] <- h[x] + 1
}

where, if x is not yet a key, h[x] on the right-hand side of the assignment should return zero (like e.g. a C++ STL map with numeric values).

As far as I can see, the only sensible way to correctly implement my pseudocode above is to wrap the h[x]<- assignment in a tryCatch() clause. It would be thus nice to have either:

  • an has_key() method to check the presence of x in keys(h) in constant time, or
  • the possibility to set a default (R object) value to missing keys.

If you think any of these two features are worth implementing, I could try to provide some starting code!

Hope this helps, Thanks.

Valerio

vgherard avatar Apr 14 '21 12:04 vgherard