喷板的解释



在 http://learnxinyminutes.com/docs/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 矩阵,也许不是在编程环境中想象数组的最佳方式?

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

您似乎掌握了该机制以及它们的作用/方式,但正在努力使用它。我明白了。

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

例如:

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,事实证明,根据我的经验,这比参数本身更有用。

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

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

最新更新