3

I understand Julia can apply element-wise argument to a function by f.(x) in v0.6

x = [1, 2, 3]
f = x->3x
@assert f.(x) = [3, 6, 9]

Now, I define f as 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

I want to apply arguments to element-wise function like above syntax, not using map, [_f(x) for _f in f]

Can someone be familiar with this issue?

Hiroaki
  • 47
  • 4

3 Answers3

10

You can broadcast the pipe operator (|>), e.g.

x .|> f
Michael K. Borregaard
  • 7,864
  • 1
  • 28
  • 35
3

You have to take care how to define x and f, in some cases you will fail. Your first x applied on your last f will fail.

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")
stefan bachert
  • 9,413
  • 4
  • 33
  • 40
0

Here's another possibility:

((f, x)->f(x)).([f1, f2], x)
DNF
  • 11,584
  • 1
  • 26
  • 40