Function depending on the global variable inside module

Yes.

First, for type stability. (cf. Avoid fields with abstract type)

Second, for composability with various packages that cannot be predicted in advance. (Example: Composability with MonteCarloMeasurements.jl)

If you really don’t want to write type parameters, you can use ConcreteStructs.jl. The macro ConcreteStructs.@concrete automatically add type parameters to all fields in struct.

See [ANN] ConcreteStructs.jl - Cut the boilerplate when concretely parameterizing structs

Small working example. (Note that we have an issue someone should solve. Play nicely with other struct def macros · Issue #4 · jonniedie/ConcreteStructs.jl · GitHub)

using ConcreteStructs

Base.@kwdef @concrete struct Problem g; y0; v0; tspan end
Problem(;
    g = 9.80665,
    y0 = 0.0,
    v0 = 30.0,
    tspan = (0.0, 8.0)
) = Problem(g, y0, v0, tspan)

prob1 = Problem()

Output: Problem{Float64, Float64, Float64, Tuple{Float64, Float64}}(9.80665, 0.0, 30.0, (0.0, 8.0))

prob2 = Problem(v0 = 100.0)

Output: Problem{Float64, Float64, Float64, Tuple{Float64, Float64}}(9.80665, 0.0, 100.0, (0.0, 8.0))

using MonteCarloMeasurements
prob3 = Problem(y0 = 0.0 ± 0.0, v0 = 30.0 ± 1.0)

Output: Problem{Float64, Particles{Float64, 2000}, Particles{Float64, 2000}, Tuple{Float64, Float64}}(9.80665, 0.0, 30.0 ± 1.0, (0.0, 8.0))

1 Like