Search code examples
rcode-golf

How do I turn on function name completion?


In golfing, one tries to complete a puzzle in as few characters as possible, generally using the base language only. One trick for golfing in R is to use partial completion so that e.g. rle(...)$length can be shortened to rle(...)$l. How does one turn on function name completion in R, preferably in as few characters as possible?


Solution

  • `?` <- function(object){
        object <- deparse(substitute(object))
        splt <- strsplit(object,"(",fixed=TRUE)[[1]]
        object <- splt[1]
        if(length(splt)>1)
            func <- paste("(",splt[2],collapse="")
        else
            func <- ""
        envs <- sapply(search(),as.environment)
        objs <- do.call("c",lapply(envs,function(x) ls(envir=x,all.names=TRUE)))
        matches <- objs[grep(object,objs)]
        objectMatch <- matches[which.min(nchar(matches))][1]
        res <- eval(parse(text=paste(objectMatch,func,collapse="")), envir = parent.frame())
        res
    }
    

    This overloads the help operator to provide the shortest object matching the regular expression provided. For example:

    > ?as.ch
    function (x, ...)  .Primitive("as.character")
    > a<-1
    > ?as.ch(a)
    [1] "1"