Idiomatic evaluate for scalar, allocate and broadcast for array?

bremez
Mon, 19 Jan 2026 19:11:21 +0000
General Usage

In several cases I’ve come across the following pattern:

function f(x; kwargs...)
#intense pre-computation that depend on kwargs but not x
result = 0.0 * x; # one way to preallocate for e.g. x::Vector, but not for scalars
for i in contributions
    if isa(x, Number)
         result += @. (complicated expression involving x, i, and the precomputations)
    else
        @. result += (same expression)
    end
end
return result
end

The main issue is that @. result += ... errors if result is a scalar. The intense precomputations make externally mapping f costly. One solution is to dispatch f(x::Number; kwargs...) = f([x]; kwargs...), but that array allocation looks awkard to me. The one decent solution I can think of is putting the loop over contributions behind a function barrier, e.g. return sumofcontributions(x,...), but that in my cases requires passing many variables from f’s precomputations to sumofcontributions, which also feels inelegant.

What would be the nominal idiomatic pattern here?

8 posts - 5 participants