我知道Julia可以通过f.(x(将元素参数应用于函数 在 v0.6 中
x = [1, 2, 3]
f = x->3x
@assert f.(x) = [3, 6, 9]
现在,我将 f 定义为 Array{Function, 1}。
f1(x) = 3x
f2(x) = 4x
f = [f1, f2]
x = 2
@assert isa(f, Array{Function,1}) == true
# f.(x) is unavailable
我想像上面的语法一样将参数应用于逐元素函数,而不是使用map
,[_f(x) for _f in f]
有人可以熟悉这个问题吗?
您可以广播管道运算符 (|>
(,例如
x .|> f
你必须注意如何定义x和f,在某些情况下你会失败。应用于最后一个 f 的第一个 x 将失败。
julia> 5 .|> [x->2x, x->7x]
2-element Array{Int64,1}:
10
35
julia> [2, 5] .|> [x->2x, x->7x]
2-element Array{Int64,1}:
4
35
julia> [2 5] .|> [x->2x, x->7x]
2-element Array{Int64,2}:
4 10
14 35
julia> [2 5] .|> [x->2x x->7x]
1×2 Array{Int64,2}:
4 35
julia> [2, 5] .|> [x->2x x->7x]
2×2 Array{Int64,2}:
4 14
10 35
julia> [2 3 5] .|> [x->2x x->7x]
ERROR: DimensionMismatch("arrays could not be broadcast to a common")
julia> [2, 3, 5] .|> [x->2x, x->7x]
ERROR: DimensionMismatch("arrays could not be broadcast to a common")
julia> x = [1, 2, 3]; f = [x->2x, x->3x]; x .|> f
ERROR: DimensionMismatch("arrays could not be broadcast to a common")
这是另一种可能性:
((f, x)->f(x)).([f1, f2], x)