您可以通过带有省略号的元组轻松地将"正常"(即非关键字)变量值传递给函数,例如:
julia> f(x, y, z) = x + y + z;
julia> f(0, 1, 2)
3
julia> varvalues = 0, 1, 2
(0,1,2)
julia> f(varvalues...)
3
Run Code Online (Sandbox Code Playgroud)
但对于关键字变量,如何通过变量传递关键字和相应的变量值?比如说(原谅这个愚蠢的例子):
julia> function g(x, y, z; operation = "add", format = "number")
operation == "add" && format == "number" && return x + y + z
operation == "add" && format == "string" && return string(x + y + z)
operation == "times" && format == "number" && return x * y * z
operation == "times" && format == "string" && return string(x * y * z)
end; # yep, I know this not type-stable
julia> g(0, 1, 2, operation = "times", format = "string")
"0"
julia> g(varvalues..., operation = "times", format = "string") # varvalues = (0,1,2)
"0"
Run Code Online (Sandbox Code Playgroud)
所以我想定义两个变量,类似于varvalues上面的:keywords使用关键字和keywordvarvalues相应的变量值,可以传递给函数g.像这样的东西,但是有效:
julia> keywords = :operation, :format
(:operation,:format)
julia> keywordvarvalues = "times", "string"
("times","string")
julia> g(varvalues..., keywords... = keywordvarvalues...)
ERROR: MethodError: no method matching broadcast!...
Run Code Online (Sandbox Code Playgroud)
我想我总是可以从keywords和组成这个字符串keywordvarvalues:
expressionstring = """g(varvalues..., operation = "times", format = "string")"""
Run Code Online (Sandbox Code Playgroud)
然后解析它,但那是多么糟糕的做法,不是吗?
这有效:
julia> keywords = :operation, :format
(:operation,:format)
julia> keywordvarvalues = 10, 20
(10,20)
julia> g(; operation=1, format=2) = (operation, format)
g (generic function with 1 method)
julia> g(; zip(keywords, keywordvarvalues)...)
(10,20)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |