You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This commit adds two simple functions `similar_dims` (and `similar_units`)
that return a `Quantity` type with the dimensions (and units)
constrained to those of the parameters
I found myself trying to write simulation code with strongly typed
interfaces, i.e. including information about the units. Initially I
wrote my interfaces like so:
```julia
const Meters = typeof(1.0m);
circumference_of_circle(r::Meters) = pi*r^2
```
However, when trying to autodiff through this code, I run into a
problem, because `Meters` has the numerical type `Float64` baked in, and
autodiff evaluates on a type `Quantity{Dual{Float64}}` (roughly).
We can instead define `Meters` like so:
```julia
const Meters{T<:Real} = Quantity{T, dimension(1.0m), unit(1.0m)}
circumference_of_circle(r::Meters{T}) where {T} = pi*r^2
circumference_of_circle(r::Quantity{T, dimension(1.0m), unit(1.0m)}) where {T} = pi*r^2
```
but I thought a better approach would be to provide some syntactic sugar
to this "unit constraint".
With this PR, we can write
```julia
circumference_of_circle(r::similar_dims(u"m")) where {T} = pi*r^2
circumference_of_circle(r::similar_units(u"m")) where {T} = pi*r^2
```
The difference is that the first one only constrains the dimension, and
the latter constrains both dimension and unit (i.e. doesn't allow e.g. `km`).
I'm happy to receive any feedback on the idea and the naming.
Other names could be e.g. `quantity_with_dims` (but too long for my
taste), or `dims_as` etc., but `similar` is already Julia lingo and
feels appropriate in this context.
0 commit comments