Unitful.jl
                                
                                 Unitful.jl copied to clipboard
                                
                                    Unitful.jl copied to clipboard
                            
                            
                            
                        How to dispatch on molar mass?
Hello,
I'd like to differentiate my functions based on if the user provided a Mass dimension or a molar mass dimension. Unitful already has the Unitful.Mass to make it easy to dispatch on mass but I've been majorly struggling to dispatch on molar mass. My attempt is below:
molar_mass_unit = Unitful.Dimensions{(Unitful.Dimension{:Mass}(1//1), Unitful.Dimension{:Amount}(-1//1))}
function f(a::Unitful.Quantity{T, molar_mass_unit, U}) where {T,U}
       println("molar mass function")
end
I also tried using
 molar_mass_unit = Unitful.Dimensions{(Unitful.๐,Unitful.๐^-1)}
Ok like 50th thing I tried worked but I still don't get why the above doesn't.
If I define @derived_dimension MolarMass ๐/๐ true I can just use MolarMass. I also created a PR to add this as one of the default derived units.
My attempt is below:
molar_mass_unit = Unitful.Dimensions{(Unitful.Dimension{:Mass}(1//1), Unitful.Dimension{:Amount}(-1//1))} function f(a::Unitful.Quantity{T, molar_mass_unit, U}) where {T,U} println("molar mass function") end
This doesnโt work for two reasons:
- The second type parameter must be an instance of a Dimensionstype, not a type itself (i.e.,molar_mass_unit()instead ofmolar_mass_unit)
- Unitful uses a canonical ordering of the dimensions in the Dimensionstype parameter. A value of1u"kg/mol"(and any other quantity or unit of molar mass) has dimension
 As you can see, the order of the dimensions is switched compared to your attempt. Thatโs why it doesnโt work.julia> typeof(dimension(1u"kg/mol")) Unitful.Dimensions{(Unitful.Dimension{:Amount}(-1//1), Unitful.Dimension{:Mass}(1//1))}
I also tried using
molar_mass_unit = Unitful.Dimensions{(Unitful.๐,Unitful.๐^-1)}
This doesnโt work because Unitful.๐ and Unitful.๐ are already instances of the type Unitful.Dimensions, not Unitful.Dimension. The following works:
molar_mass_unit = Unitful.๐ * Unitful.๐^-1
We should have better documentation for this. I think we should
- Feature @derived_dimensionmore prominently in the manual.
- Improve the part of the Quantitydocstring which explains thatDis an instance whileUis a type:The type parameters D :: Unitful.DimensionsandU <: Unitful.Units.
Yeah definitely add another example to the dispatch part. Its a super useful and cool feature.