A simple way to do this is to store a vector of the powers.
For example momentum is kilogram * meter / second, which is MASS^1 * LENGTH^1 * TIME^-1
As a vector, this can be represented as (1,1,-1) where the positions are M, L, T respectively.
In that format velocity is represented as (0,1,-1), acceleration is (0,1,-2), etc...
This is automatically canonicalised and much easier to manipulate than a tree of operations.
Of course, this assumes uniform units such as CGS or MKS in something sane like the metric system. Conversion back and forth is generally straightforward, as long as the types encode the system used. E.g.: CGS<1,1,-1> and MKS<1,1,-1> both represent momentum, but at different scales.
Imperial also works, and other base units can be added to extend the system. This can include things like current, temperature, moles, etc...
See: https://en.wikipedia.org/wiki/Dimensional_analysis