Broadcasting not on all arguments

I find myself thinking in common OOP terms and trying to have object representing a model that has some method to do something to outside data.

So I thought, in Julia, the model should likely be a struct and the method should accept the struct as an argument.

The simplified example I can come up with:

mutable struct CarModel
    # some car properties
    consumption
end

function predict_consumption(carmodel, distance)
    return carmodel.consumption*distance
end

myCar = CarModel(10)

consumption_values = predict_consumption(myCar, 10)

However, when doing so, I cannot use dot-broadcasting on the input data

distances = 0:100
consumption_values = predict_consumption.(myCar, distances)

ERROR: LoadError: MethodError: no method matching length(::CarModel)

I can fully imagine, that this is the most sensible behavior, since Julia cannot find out if myCar is to be broadcasted on or if it is a scalar.

Is there some elegant or commonly used approach for such a scenario of mimicking mehtods inside objects by functions taking structs + actual parameters?

Either you want

predict_consumption.(Ref(myCar), distances)

or define something like

Base.broadcastable(x::CarModel) = Ref(x)

to do this automatically for your type. See the manual on broadcasting.

7 Likes