11

http://learnxinyminutes.com/docs/julia/上阅读有关 Julia 的信息时,我遇到了这个问题:

# You can define functions that take a variable number of
# positional arguments
function varargs(args...)
    return args
    # use the keyword return to return anywhere in the function
end
# => varargs (generic function with 1 method)

varargs(1,2,3) # => (1,2,3)

# The ... is called a splat.
# We just used it in a function definition.
# It can also be used in a fuction call,
# where it will splat an Array or Tuple's contents into the argument list.
Set([1,2,3])    # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays
Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3)

x = (1,2,3)     # => (1,2,3)
Set(x)          # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples
Set(x...)       # => Set{Int64}(2,3,1)

我敢肯定这是一个非常好的解释,但是我无法掌握主要思想/好处。

据我目前了解:

  1. 在函数定义中使用 splat 允许我们指定我们不知道函数将给出多少个输入参数,可能是 1,可能是 1000。不要真正看到这样做的好处,但至少我理解 (我希望)这个概念。
  2. 使用 splat 作为函数的输入参数会......究竟是什么?我为什么要使用它?如果我必须将数组的内容输入到参数列表中,我将使用以下语法:some_array(:,:)(对于 3D 数组,我将使用 some_array(:,:,:) 等)。

我认为我不明白这一点的部分原因是我在努力定义元组和数组,是 Julia 中的元组和数组数据类型(如 Int64 是一种数据类型)吗?或者它们是数据结构,什么是数据结构?当我听到数组时,我通常会想到 2D 矩阵,这可能不是在编程上下文中想象数组的最佳方式?

我意识到你可能会写整本关于什么是数据结构的书,我当然可以用谷歌搜索它,但是我发现对一个主题有深刻理解的人能够用更简洁(也许是简化)来解释它那么让我们说维基百科文章可以,这就是我问你们(和女孩)的原因。

4

1 回答 1

12

您似乎了解了机制以及它们的作用方式/作用,但是却在为使用它的目的而苦苦挣扎。我明白了。

我发现它们对于我需要传递未知数量的参数并且不想在以交互方式使用函数时在传递它之前先构造一个数组的事情很有用。

例如:

func geturls(urls::Vector)
   # some code to retrieve URL's from the network
end
geturls(urls...) = geturls([urls...])

# slightly nicer to type than building up an array first then passing it in.
geturls("http://google.com", "http://facebook.com")

# when we already have a vector we can pass that in as well since julia has method dispatch
geturls(urlvector)

所以有几点需要注意。Splat 允许您将可迭代对象转换为数组,反之亦然。看到[urls...]上面的一点了吗?Julia 把它变成了一个扩展了 urls 元组的 Vector,结果证明它比我的经验中的论点更有用。

这只是证明它们对我有用的一个例子。当你使用 julia 时,你会遇到更多。

它主要用于帮助设计感觉自然使用的 api。

于 2014-11-18T00:01:58.450 回答