v0.4 中匿名函数的参数数量

Number of parameters for an anonymous function in v0.4

我的包裹里有以下物品:

"""
numparameters(f)

Returns the number of parameters of `f` for the method which has the most parameters.
"""
function numparameters(f)
  if length(methods(f))>1
    warn("Number of methods for f is greater than 1. Choosing linearity based off of method with most parameters")
  end
  numparm = maximum([length(m.sig.parameters) for m in methods(f)])
  if VERSION < v"0.5-"
    return numparm
  else
    return (numparm-1) #-1 in v0.5 since it add f as the first parameter.
  end
end

这适用于泛型函数,因此它也适用于 v0.5+ 上的匿名函数。但是,v0.4 上的匿名函数没有方法,因此会出错。我想知道是否有人知道解决方法。

在 0.4 上,这应该适用于匿名函数:

length(Base.uncompressed_ast(f.code).args[1])

这从 AST 中提取形式参数列表并获取其长度。然而,这是相当昂贵的,所以你不应该经常这样做。