gpt4 book ai didi

r - 为什么有些原语有字节码而有些没有?

转载 作者:行者123 更新时间:2023-12-04 01:04:03 25 4
gpt4 key购买 nike

我注意到当我调用 args 时在 一些在原始函数中,字节码也出现了。但在其他原语上,没有字节码出现。例如

args(length)
# function (x)
# NULL
args(list)
# function (...)
# NULL
# <bytecode: 0x44a0f38>

这是为什么?

起初我以为它可能与 ...有关论点,但以下反驳了该理论。
args(dim)
# function (x)
# NULL
args(unclass)
# function (x)
# NULL
# <bytecode: 0x44a0450>

让我感到困惑的是,字节码只出现在其中一些中,而不出现在其他中。我一直认为所有原语都是特殊的,并且它们都共享相同的“属性”(因为没有更好的词,而不是实际的 R 属性)。

最佳答案

正如 agstudy 所指出的,这与 args 的方式有关。打印东西。即是否args在其输出中包含字节码行并不是函数是否经过字节编译的可靠指标。比较:

args(writeLines)
## function (text, con = stdout(), sep = "\n", useBytes = FALSE)
## NULL

writeLines
## function (text, con = stdout(), sep = "\n", useBytes = FALSE)
## {
## if (is.character(con)) {
## con <- file(con, "w")
## on.exit(close(con))
## }
## .Internal(writeLines(text, con, sep, useBytes))
## }
## <bytecode: 0x000000001bf3aeb0>

我们可以比较 args 的字节码行的打印。与标准功能打印。
arg_shows_bytecode <- function(fn)
{
output <- capture.output(args(fn))
grepl("^<bytecode", output[length(output)])
}

printing_shows_bytecode <- function(fn)
{
output <- capture.output(print(fn))
length(output) > 1 && grepl("^<bytecode", output[length(output) - 1])
}

base_fns <- Filter(is.function, mget(ls(baseenv()), baseenv()))
yn_args <- vapply(base_fns, arg_shows_bytecode, logical(1))
yn_print <- vapply(base_fns, printing_shows_bytecode, logical(1))

值得注意的是, args 的所有函数显示字节码信息是原语。
head(base_fns[yn_args])
## $`%*%`
## function (x, y) .Primitive("%*%")
##
## $as.call
## function (x) .Primitive("as.call")
##
## $attr
## function (x, which, exact = FALSE) .Primitive("attr")
##
## $`attr<-`
## function (x, which, value) .Primitive("attr<-")
##
## $attributes
## function (obj) .Primitive("attributes")
##
## $`attributes<-`
## function (obj, value) .Primitive("attributes<-")

反之则不然:一些基函数在 args不显示字节码信息是原语;其他人不是。
yn_prim <- vapply(base_fns, is.primitive, logical(1))
table(yn_args, yn_print, yn_prim)
## , , yn_prim = FALSE
##
## yn_print
## yn_args FALSE TRUE
## FALSE 0 988
## TRUE 0 0
##
## , , yn_prim = TRUE
##
## yn_print
## yn_args FALSE TRUE
## FALSE 119 0
## TRUE 63 0

所以基础包中的非原始函数全部编译,但是 args没有提到它。原始函数在打印时不显示字节码消息,并且在使用 args 调用时仅显示字节码消息。

关于r - 为什么有些原语有字节码而有些没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26030203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com