在Julia中区分动态变量和静态变量



在Julia中,是否有像isdynamic()这样的函数来显示给定变量是"动态"还是"静态"类型?例如,我假设下面代码中的ab分别是动态和静态变量,这里的"动态"是指变量可以表示任何数据类型。如果我运行@code_warntype, ab分别显示为AnyInt64,但我想知道是否可以用某些函数显示实际的内部表示。这是不可能的,因为内部表示的确定取决于整个函数(加上,当变量依赖于它时,实际参数的类型)而不是调用isdynamic( a )之前的代码吗?

function test()
    a = 1
    b::Int = 1
    @show typeof( a )    # Int64
    @show typeof( b )    # Int64
    a = 3.0
    b = 3.0
    @show typeof( a )   # Float64
    @show typeof( b )   # Int64
    a = 3.2      # okay
    # b = 3.2    # InexactError
end
test()
# @code_warntype test()   # after eliminating @show... statements

好的,尝试将以下代码放入test函数体:

function test()
:
:
    vinfo = code_lowered(test,())[1].args[2][1]
    aind = findfirst(x->x[1]==:a,vinfo)
    bind = findfirst(x->x[1]==:b,vinfo)
    if aind > 0
        println("inference-type of a = $(vinfo[aind][2])")
    end
    if bind > 0
        println("inference-type of b = $(vinfo[bind][2])")
    end
end

,运行test()。当推理引擎计算并在内部存储变量时,这将显示变量之间的差异。通过查看代码修复了这个问题,所以也许更像内部专家的人有更好的答案。

对于像OP那样的isdynamic函数,我们可以有:

function isdynamic(f,args,symbol)
    vi=code_lowered(f,args)[1].args[2][1]
    (ind=findfirst(x->x[1]==symbol,vi))>0 ? vi[ind][2]==:Any : false
end
isdynamic(test,(),:a) # true
isdynamic(test,(),:b) # false