kirillseva / cacher

In memory cache interface for R
4 stars 4 forks source link

Define operators #1

Open robertzk opened 8 years ago

robertzk commented 8 years ago

Define [ etc operators

peterhurford commented 8 years ago

What does this mean?

kirillseva commented 8 years ago

AKA

cache <- LRUcache(3)
cache['key'] <- 'value'  # same as cache$set('key', 'value')
cache['key']  # same as cache$get('key')

I wonder what I can use as syntactic sugar for exists and forget?

abelcastilloavant commented 6 years ago

@robertzk were there other operators worth defining?

robertzk commented 6 years ago

Maybe %in% for key check, [, [[ for access.

kirillseva commented 6 years ago

I like %in%! But %in% uses match under the hood which is just a call to .Internal and not a UseMethod

robertzk commented 6 years ago

There's a way to generate generics for any built-in using shadowing. It's either the below or possibly standardGeneric with signatures, but it's doable.

`%in%` <- function(x, table) {
  UseMethod("%in%")
}
robertzk commented 6 years ago

There's always this (though I think there's a better way to do it than I did there, if not only to pass along non-standard evaluation correctly).

kirillseva commented 6 years ago

Yeah I'm not a big fan of that. But to be able to check if things are in cache using %in% is too appealing

robertzk commented 6 years ago

I believe correct is the below, which should create a shadow over the built-in.

setMethod("%in%", signature = c("ANY", "LRUCache"), def = function(x, table) {
})
robertzk commented 6 years ago

@kirillseva @peterhurford @abelcastilloavant Yep! Adding that to a blank package yields:

> devtools::document()
Updating package.name documentation
Loading package.name
Creating a generic function for ‘%in%’ from package ‘base’ in package ‘package.name’
in method for ‘%in%’ with signature ‘"ANY","LRUCache"’: no definition for class “LRUCache”
Updating roxygen version in /Users/robertk/tmp/pkgx/DESCRIPTION
Writing NAMESPACE
Writing package.name.Rd
> devtools::load_all()
Loading package.name
Creating a generic function for ‘%in%’ from package ‘base’ in package ‘package.name’
in method for ‘%in%’ with signature ‘"ANY","LRUCache"’: no definition for class “LRUCache”
> `%in%`
standardGeneric for "%in%" defined from package "base"

function (x, table)
standardGeneric("%in%")
<environment: 0x7fb3f0e5d978>
Methods may be defined for arguments: x, table
Use  showMethods("%in%")  for currently available ones.
> 'a' %in% letters
[1] TRUE
> ('a' %in% structure(list(), class = "LRUCache"))
NULL