Unitful, dispatch on u"1/s" and u"rad/s"

Hello everyone,

This is a follow up question from this topic.

Now instead of just the unit I would like to have different quantities. Let me explain.
I want to dispatch on units of 1/s and rad/s.

Now I do the following:

my_units(quantity :: typeof(1.0u"1/s")) = "only works for real value of Hz"
my_units(quantity :: typeof(1.0u"rad/s")) = "only works for real value of radHz"

This works only for real values.
My question is how can I make this work for any type, like ints or rational.
I know I can do the following:

my_units(quantity :: Unitful.Frequency) = "works for real and integer values of Hz"

The problem is that if I give radHz, I will get the same result. How can define a method that dispatches on radHz for any type of the value?

Thanks in advance,

It’s a bit tricky, but all the information is there: https://painterqubits.github.io/Unitful.jl/latest/manipulations/

You can see that the information is encoded in a type Quantity{T,D,U}:

julia> typeof(1.0u"1/s")

julia> typeof(1.0u"rad/s")
Quantity{Float64,𝐓^-1,Unitful.FreeUnits{(rad, s^-1),𝐓^-1,nothing}}

T is the number type, and D and U are dimensions and units, respectively.

It is enough for your use to dispatch on the unit part only, keeping the type T and dimension D as free parameters. We use the unit function to select the part of the type we need.

my_units(q::Quantity{T,D,typeof(unit(1.0u"1/s"))}) where {T<:Real,D} = "only works for real value of Hz"
my_units(q::Quantity{T,D,typeof(unit(1.0u"rad/s"))}) where {T<:Real,D}  = "only works for real value of radHz"

This now works as expected:

julia> my_units(1.0u"rad/s")
"only works for real value of radHz"

julia> my_units(1.0u"1/s")
"only works for real value of Hz"

Thanks a lot!
I had tried something similar but I missed the key point


Thanks again!