Hello,
Using Unitful.jl, you can dispatch on dimensions or specific units. For example, you can write a method that takes any length quantity:
using Unitful: m, ft, Length
f(x::Length) = println("Got length: $x")
Or a function that takes only meters:
f(x::typeof(1m)) = println("Got meters: $x")
I could also write a function that takes two arguments with the same length unit
f(x::T, y::T) where T <: Length = println("Got same units: ($x, $y)")
But is there a way that I can write a function that requires that both of its arguments have the same dimension, but not necessarily the same unit?
To answer my own question, I’ve found the following:
function g(x::AbstractQuantity{<:Number,D}, y::AbstractQuantity{<:Number,D}) where D
println("same dims: $x + $y = $(x+y)")
end
which works as expected:
julia> g(1m, 2ft)
same dims: 1 m + 2 ft = 1006//625 m
I feel compelled to bound D, but I don’t think it’s actually possible, because typeof(1m)
is Quantity{Int64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}
, and 𝐋
is a value, not a type. And if I recall, you can’t constrain values used as type parameters.
Also, I’m not sure if there’s a good reason to use AbstractQuantity
over just Quantity
. Are there other useful AbstractQuantity
s out there?
If anyone else has another solution, I’d love to see it.
Thanks,
Oliver