如何创建n个变量的函数(Julia) [英] How to create a function of n variables (Julia)
问题描述
对于固定的 n
,我想创建一个具有 n
变量的函数
For a fixed n
, I would like to create a function with n
variables
f(x_1, ..., x_n)
例如,如果 n = 3
,我想创建一个算法,
For example if n=3
, I would like to create an algorithm such that
f(x_1, x_2, x_3) = x_1 + x_2 + x_3
为每个 n
个算法都很好:
f(x_1, ..., x_n) = x_1 + ... + x_n
我不知道如何声明该函数以及如何创建 n
变量.
I don't know how to declare the function and how can create the n
variables.
感谢您的帮助,
推荐答案
在Julia中,您可以做
In Julia you can just do
function f(x...)
sum(x)
end
现在:
julia> f(1,2,3)
6
请注意,在函数 f
中, x
仅被视为 Tuple
,因此您可以做任何想做的事情(包括询问类型)元素等).
Note that within the function f
, x
is just seen as a Tuple
so you can do whatever you want (including asking for type of elements etc).
通常,您可以定义函数f(x ...; y ...)
.让我们试试吧
More generally you can define function f(x...;y...)
. Let us give it a spin
function f(x...;y...)
@show x
@show Dict(y)
end
现在运行它:
julia> f(1,2,"hello";a=22, b=777)
x = (1, 2, "hello")
Dict(y) = Dict(:a => 22, :b => 777)
Dict{Symbol, Int64} with 2 entries:
:a => 22
:b => 777
最后,另一种(也许不太优雅)的方式可能是:
Finally, another one (perhaps less elegant) way could be:
g(v::NTuple{3,Int}) = sum(v)
这迫使 v
成为 3
元素 Tuple
,并且 g
被称为 g((1,2,3))
This forces v
to be a 3
-element Tuple
and g
be called as g((1,2,3))
这篇关于如何创建n个变量的函数(Julia)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!