我有一个我在向量上定义的大功能,但我希望它也可以使用单个值。我希望第一个参数的类型是向量或数字。
我转向以下内容:
function bigfunction(x::Vector, y::Float64=0.5)
# lots of stuff
z = x .+ y
return z
end
bigfunction(x::Number) = bigfunction()
该函数适用于矢量,但不适用于数字。
bigfunction([0, 1, 3])
bigfunction(2)
我有时会和Union{}
做点什么吗?或者以不同的方式重新定义方法?
这个问题和回答有助于向我展示Chris Rackauckas在伟大的blog post上对朱莉娅的类型派遣所提出的观点。
我已将响应整理到以下代码中:
# I ran this only in Julia 1.0.0.
## ========== Original function ==========
## function bigfunction(x::Vector, y::Float64=0.5)
## # lots of stuff
## z = x .+ y
## return z
## end
## bigfunction(x::Number) = bigfunction()
## println(bigfunction([0, 1, 3]))
## println(bigfunction(2))
## ---------- Output has ERROR ----------
## [0.5, 1.5, 3.5]
## ERROR: LoadError: MethodError: no method matching bigfunction()
# ========== Answer Suggested by Picaud Vincent in comments ==========
# Note use of Union in function signature.
function bigfunction(x::Union{Vector, Number}, y::Float64=0.5)
# lots of stuff
z = x .+ y
return z
end
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5
# ========== Answer Suggested by Robert Hönig in comments ==========
# Note change in line right after function definition.
function bigfunction(x::Vector, y::Float64=0.5)
# lots of stuff
z = x .+ y
return z
end
bigfunction(x::Number) = bigfunction([x])
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5
# ========== Answer Suggested by Chris Rackauckas ==========
# Note change in function signature using duct typing--no type for x.
function bigfunction(x, y=0.5)
# lots of stuff
z = x .+ y
return z
end
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5
还是鸭子型。请记住,功能始终是自动专用的,因此选择受限制的调度根本不会影响性能。
function bigfunction(x, y=0.5)
# lots of stuff
z = x .+ y
return z
end
这将是高效的,但将适用于更多类型。见this blog post on type-dispatch designs for more information。