你可以很容易地通過一個元組通過「正常」(即非關鍵字)變量值的函數以省略號,例如像:如何通過元組
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
但是對於關鍵字變量,如何通過變量傳遞關鍵字和相應的變量值?像例如(原諒傻示例):
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"
所以想以限定兩個變量,類似於上面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!...
我想我總是可以撰寫從keywords
和keywordvarvalues
這個字符串:
expressionstring = """g(varvalues..., operation = "times", format = "string")"""
,然後解析-EVAL它,但是這是prolly不好的做法,不是嗎?
分號做:) – tim
正是我想要的伎倆!謝謝。 –