如何将函数追加到数组?

时间:2016-12-10 04:08:22

标签: arrays function julia

例如,我可以创建一个包含函数的数组。

julia> a(x) = x + 1
>> a (generic function with 1 method)

julia> [a]
>> 1-element Array{#a,1}:
    a

但我似乎无法将该函数添加到空数组中:

julia> append!([],a)

>> ERROR: MethodError: no method matching length(::#a)
  Closest candidates are:
    length(::SimpleVector) at essentials.jl:168
    length(::Base.MethodList) at reflection.jl:256
    length(::MethodTable) at reflection.jl:322
    ...
   in _append!(::Array{Any,1}, ::Base.HasLength, ::Function) at .\collections.jl:25
   in append!(::Array{Any,1}, ::Function) at .\collections.jl:21

我最想做的是存储预定义的函数,以便最终将它们映射到一个值上。 E.g:

x = 0.0

for each fn in vec
    x = x + fn(x)    
end

1 个答案:

答案 0 :(得分:3)

append!用于将一个集合附加到另一个集合。 您正在寻找push!,以便为集合添加元素。

您的代码应为push!([], a)

参见文档:

julia>?append!

search: append!

append!(collection, collection2) -> collection.

Add the elements of collection2 to the end of collection.

julia> append!([1],[2,3])
3-element Array{Int64,1}:
 1
 2
 3

julia> append!([1, 2, 3], [4, 5, 6])
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

Use push! to add individual items to collection which are not already themselves in another collection. The result is of the preceding example is equivalent to push!([1, 2, 3], 4, 5, 6).

VS

julia>?push!

search: push! pushdisplay

push!(collection, items...) -> collection

Insert one or more items at the end of collection.

julia> push!([1, 2, 3], 4, 5, 6)
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

Use append! to add all the elements of another collection to collection. The result of the preceding example is equivalent to append!([1, 2, 3], [4, 5, 6]).