在Julia中,当两个args属于同一类型时,可以向量化2个arg函数:
function mysquare(n::Number, x::Number)
return n * x^2
end
println(mysquare(2, 2.)) # ⇒ 8.0
@vectorize_2arg Number mysquare
println(mysquare(2, [2., 3., 4.])) # ⇒ [8.0,18.0,32.0]
除了手动操作之外,还有一种方法可以矢量化两种不同类型的args的功能:
function mysquare(n::Int64, x::Float64)
return n * x^2
end
println(mysquare(2, 2.))
@vectorize_2arg Int64 Float64 mysquare # ⇒ wrong number of args
println(mysquare(2, [2., 3., 4.]))
答案 0 :(得分:1)
我修改了vectorize_2arg宏的代码。我不确定我是否完全理解这里的所有含义,但它确实有效:
macro vectorize_2arg_full(S1,S2,f)
S1 = esc(S1); S2 = esc(S2); f = esc(f); T1 = esc(:T1); T2 = esc(:T2)
quote
($f){$T1<:$S1, $T2<:$S2}(x::($T1), y::AbstractArray{$T2}) =
reshape([ ($f)(x, y[i]) for i=1:length(y) ], size(y))
($f){$T1<:$S1, $T2<:$S2}(x::AbstractArray{$T1}, y::($T2)) =
reshape([ ($f)(x[i], y) for i=1:length(x) ], size(x))
function ($f){$T1<:$S1, $T2<:$S2}(x::AbstractArray{$T1}, y::AbstractArray{$T2})
shp = promote_shape(size(x),size(y))
reshape([ ($f)(x[i], y[i]) for i=1:length(x) ], shp)
end
end
end
function mysquare(n::Int64, x::Float64)
return n * x^2
end
println(mysquare(2, 2.))
@vectorize_2arg_full Int64 Float64 mysquare
println(mysquare(2, [2., 3., 4.]))
有人可以对其进行代码审核吗?
修改强>
我posted that on a Julia mailing list:可以使用
@vectorize_2arg Number mysquare
为此。无需调整。