2
我可以解開一個元組。我試圖編寫一個函數(或宏),從類型構造函數Parameters()
的實例中解壓縮這些函數的子集。也就是說,我知道該怎麼做:Julia:風格解壓
a,b,c = unpack(p::Parameters)
但我願做這樣的事情:
b,c = unpack(p::Parameters, b,c)
,或者甚至懶:
unpack(p::Parameters, b, c)
這是爲了避免寫作例如:
function unpack_all_oldstyle(p::Parameters)
a=p.a; b=p.b; c=p.c; ... z=p.z;
return a,b,c,...,z
end
有東西我的方法錯了,但希望有一個解決辦法。
如果從我的問題的措辭不清楚,我是一個完全無知。我讀到這裏拆包省略號:how-to-pass-tuple-as-function-arguments
workspace()
"module UP tests Unpacking Parameters"
module UP
"this type declaration initiates a constructor function"
type Parameters
a::Int64
b::Int64
c::Int64
end
"this function sets default parameters and returns a tuple of default values"
function Parameters(;
a::Int64 = 3,
b::Int64 = 11,
c::Int64 = 101
)
Parameters(a, b, c)
end
"this function unpacks all parameters"
function unpack_all(p::Parameters)
return p.a, p.b, p.c
end
"this function tests the unpacking function: in the body of the function one can now refer to a rather than p.a : worth the effort if you have dozens of parameters and complicated expressions to compute, e.g. type (-b+sqrt(b^2-4*a*c))/2/a instead of (-p.b+sqrt(p.b^2-4*p.a *p.c))/2/p.a"
function unpack_all_test(p::Parameters)
a, b, c = unpack_all(p)
return a, b, c
end
"""
This function is intended to unpack selected parameters. The first, unnamed argument is the constructor for all parameters. The second argument is a tuple of selected parameters.
"""
function unpack_selected(p::Parameters; x...)
return p.x
end
function unpack_selected_test(p::Parameters; x...)
x = unpack_selected(p, x)
return x
end
export Parameters, unpack_all, unpack_all_test, unpack_selected, unpack_selected_test
end
p = UP.Parameters() # make an instance
UP.unpack_all_test(p)
## (3,11,101) ## Test successful
UP.unpack_selected_test(p, 12)
## 12 ## intended outcome
UP.unpack_selected_test(p, b)
## 11 ## intended outcome
UP.unpack_selected_test(p, c, b, a)
## (101,11,3) ## intended outcome
我想再次爲您的編輯upvote:非常有用的解釋如何解決我的僞代碼!謝謝! – PatrickT