【发布时间】:2021-02-04 12:25:08
【问题描述】:
我有几个函数使用不同的方法计算同一件事。我现在想将它们捆绑在一个主函数中,并带有一个用于选择方法的关键字参数。我想出的结构看起来……像下面的最小示例。这背后的想法是将特定函数分配给通用函数名称,因为它在函数内部多次使用,我不想在多个地方使用 if else .. 结构。
function testfun(input::Real; method::String = "a")
if method == "a"
println("Method a was chosen")
calculate(x) = 2x # in the real code methods are assigned here, but the errors are the same
elseif method == "b"
println("Method b was chosen")
calculate(x) = 3x
else
throw(DomainError(method))
end
return calculate(input)
end
但是这段代码不像预期的那样工作并生成:
testfun(1) # -> 3, but expected 2
testfun(1, method = "a") # -> 3, but expected 2
testfun(1, method = "b") # -> ERROR: UndefVarError: calculate not defined, but expected 3
testfun(1, method = "c") # throws the correct DomainError
当 println() 正确触发时,我在这里缺少什么来解释这种行为? Julia 版本是 1.5。 构建此类函数的正确/最佳方法是什么?
【问题讨论】:
标签: julia