Broadcasting a scalar

Let’s say I have a function like

function F(x::Vector{T}, y) where T
  for a,b in zip(x,y):
    do_something(a, b)
  end
end

Now suppose y can be either a vector or a scalar. To handle this, one choice would be just create another

function F(x::Vector{T}, y::T) where T
  for a in x:
    do_something(a, y)
  end
end

But just for my own education, I’m wondering if I can just have one function F that accepts 2 Vectors, and then when a scalar is passed, broadcast the scalar? What would that look like? Would it be as efficient as dispatching to 2 different functions (one for Vector, one for Scalar)?

You can use generators to “broadcast” your scalar into your vector version.

function F(x::Vector{T}, y::T) where T
   F(x, y for i in 1:length(x))
end

Of course you could also just use broadcast itself: broadcast(do_something, x, y) which will treat scalars and vectors correctly.

Normally, you would just write a function F(x,y) that accepts scalars only. Then, to apply it to vectors or a mix of vectors and scalars, you would do F.(x,y).

6 Likes

That’s great! Couldn’t be easier. Is this documented?

OK, I see it is explained here
https://docs.julialang.org/en/latest/manual/arrays.html

1 Like