【问题标题】:Explanation of splatsplat的解释
【发布时间】:2015-01-14 23:23:25
【问题描述】:

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 矩阵,这可能不是在编程上下文中想象数组的最佳方式?

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

【问题讨论】:

    标签: arrays tuples julia splat


    【解决方案1】:

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

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

    例如:

    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,结果证明这比我的经验中的参数本身更有用。

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

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

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 2018-01-25
      • 2023-03-16
      • 2017-08-08
      • 1970-01-01
      • 2015-02-23
      • 2016-02-12
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多