在Julia中向函数传递可选参数的有效方法
我想在Julia中创建一个接受可选参数的函数 让我们称之为“BMI”,它本身就是一个函数,因此,如果不包含此可选参数,“dou_something”将跳过一块指令 就是说,在Julia中向函数传递可选参数的有效方法,julia,Julia,我想在Julia中创建一个接受可选参数的函数 让我们称之为“BMI”,它本身就是一个函数,因此,如果不包含此可选参数,“dou_something”将跳过一块指令 就是说, function do_something(age, height; BMI=None) print("hi, I am $age years old and my height is $height") if window!=None p
function do_something(age, height; BMI=None)
print("hi, I am $age years old and my height is $height")
if window!=None
print("My BMI is $(BMI(age,height))")
end
print("bye")
end
在朱莉娅身上实现这一点的最佳方法是什么?解决问题的方法很少。首先,您可以使用
nothing
来区分是否将BMI
传递给了您的函数
function do_something(age, height; BMI = nothing)
print("hi, I am $age years old and my height is $height")
if !isnothing(BMI)
print("My BMI is $(BMI(age,height))")
end
print("bye")
end
如果您使用的是较旧版本的Julia(我认为是1.1或更低版本),您应该使用BMI!==无
,注意双等号。这就是为什么它比使用更好=代码>。在你的特殊情况下,这看起来并不重要,但最好从一开始就养成好习惯
但同时,我建议使用多重分派,这在这里看起来可能有些过分,但它让你尝到Julia的味道和感觉,也让你能够自然地扩展你的初始声明
do_bmi(bmi::Nothing, age, height) = nothing
do_bmi(bmi, age, height) = print("My BMI is $(bmi(age,height))")
function do_something(age, height; BMI = nothing)
print("hi, I am $age years old and my height is $height")
do_bmi(BMI, age, height)
print("bye")
end
例如,如果您想让用户能够从预定义函数集中选择BMI
,该函数由一些String
缩写,那么您所要做的就是定义该函数
function do_bmi(bmi::AbstractString, age, height)
if bmi == "standard"
do_bmi((a, h) -> a^2/h, age, height)
else
println("Unknown BMI keyword $bmi")
end
end
然后像这样调用原始函数
do_something(20, 170, BMI = "standard")
这种方法很好。您可能还希望创建两个具有不同算术数的函数(即do_something(age,height)和do_something(age,height;BMI)),以消除if块(也许可以使代码更清晰)。@whilrun是的,我正试图避免创建两个函数,因为我正在编写的实际函数要复杂得多。因此,我想实现类似上面的伪代码,但是在Julia中如何实现呢?julia中不存在“None”,也不确定如何检查我们是否等于空值。julia的None是Nothing
,如果BMI==Nothing,您可以使用它,就像任何其他语言一样,它应该是Nothing
,而不是Nothing
。