2016-12-05 42 views
6
關鍵字和關鍵字變量值傳遞給函數

你可以很容易地通過一個元組通過「正常」(即非關鍵字)變量值的函數以省略號,例如像:如何通過元組

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" 

所以想以限定兩個變量,類似於上面varvalueskeywords與關鍵字和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!... 

我想我總是可以撰寫從keywordskeywordvarvalues這個字符串:

expressionstring = """g(varvalues..., operation = "times", format = "string")""" 

,然後解析-EVAL它,但是這是prolly不好的做法,不是嗎?

回答

6

這工作:

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) 
+0

分號做:) – tim

+0

正是我想要的伎倆!謝謝。 –

1

您還可以使用字典:

julia> g(; keywords...) = keywords 

julia> g(a=3, b=4) 
2-element Array{Any,1}: 
(:a,3) 
(:b,4) 

julia> d = Dict(:c=>5, :d=>6) 
Dict{Symbol,Int64} with 2 entries: 
    :c => 5 
    :d => 6 

julia> g(; d...) 
2-element Array{Any,1}: 
(:c,5) 
(:d,6)