What/Where are the attributes of a function object?

后端 未结 2 1221
不知归路
不知归路 2020-12-15 05:55

By playing around with a function in R, I found out there are more aspects to it than meets the eye.

Consider ths simple function assignment, typed directly in the c

2条回答
  •  青春惊慌失措
    2020-12-15 06:21

    I jst figured out an attribute that compiled functions (package compiler) have that is not available with attributes or str. It's the bytecode.

    Example:

    require(compiler)
    
    f <- function(x){ y <- 0; for(i in 1:length(x)) y <- y + x[i]; y }
    
    g <- cmpfun(f)
    

    The result is:

    > print(f, useSource=FALSE)
    function (x) 
    {
        y <- 0
        for (i in 1:length(x)) y <- y + x[i]
        y
    }
    
    > print(g, useSource=FALSE)
    function (x) 
    {
        y <- 0
        for (i in 1:length(x)) y <- y + x[i]
        y
    }
    
    

    However, this doesn't show with normal commands:

    > identical(f, g)
    [1] TRUE
    > identical(f, g, ignore.bytecode=FALSE)
    [1] FALSE
    > identical(body(f), body(g), ignore.bytecode=FALSE)
    [1] TRUE
    > identical(attributes(f), attributes(g), ignore.bytecode=FALSE)
    [1] TRUE
    

    It seems to be accessible only via .Internal(bodyCode(...)):

    > .Internal(bodyCode(f))
    {
        y <- 0
        for (i in 1:length(x)) y <- y + x[i]
        y
    }
    
    > .Internal(bodyCode(g))
    
    

提交回复
热议问题