Dispatch on physical quantity or creating distinct types that behave like a float

As a side note, sqrt(2*d/9.81) is the time a free falling body takes to travel a distance d.

I’m afraid you have to explicitly access the field of your types where you store the value

velocity(dist::Distance, t) = dist.d / t

if you want to avoid overloading the needed methods. Which can be automated to some extend and need really only be done for arithmetic operations and powers. Anything else takes dimensionless arguments. Then however you find yourself in need of defining and handling a whole zoo of types. After all, the division of a Distance and a Time should yield a Velocity, and so on. And you haven’t even considered units yet.

Or, you take what’s there already, embrace the power of Unitful.jl (or the new DynamicalQuantities DynamicQuantities.jl v0.7.0: fast and lightweight physical quantities) and dispatch on those types :slight_smile:

julia> using Unitful

julia> velocity(g::Unitful.Acceleration, t::Unitful.Time) = g*t
velocity (generic function with 1 method)

julia> velocity(d::Unitful.Length, t::Unitful.Time) = d/t
velocity (generic function with 2 methods)

julia> g = 9.81u"m/s^2";

julia> velocity(g, 5u"s")
49.050000000000004 m s⁻¹

julia> velocity(5u"m", 10u"s")
0.5 m s⁻¹
5 Likes