Search code examples
perlunit-conversion

Symmetric and transitive custom unit conversion in Perl


I've defined the following custom units (psuedo-code):

unix_days = unix_seconds/86400; 
nasa_seconds = unix_seconds - 946728000; 

This lets me directly convert unix_seconds to unix_days or convert unix_seconds to nasa_seconds.

However, I can't directly convert unix_days back to unix_seconds without writing another formula.

Similarly, I can't convert nasa_seconds to unix_days without writing additional formulas.

Is there a clever Perl subroutine or package that lets me do this without writing additional functions? More specifically, a custom unit conversion package that:

  • Can divine the inverse of a unit conversion function. For example, the opposite of f(x)=x/86400 is g(y)=y*86400.

  • Can apply transitivity as needed. For example, if unix_seconds = nasa_seconds + 946728000 (by functional inverse) and unix_days = unix_seconds/86400, we can combine these to convert directly from nasa_seconds to unix_days.

I'm OK with writing my conversion formulas in unusual ways if needed. For example, Celsius to Fahrenheit could be written as:

C to F: *1.8 +32 

This form is easy to invert: just follow the steps backwards and in reverse, namely:

F to C: -32 /1.8 

Does such a thing exist?


Solution

  • Physics::Unit should provide the facilities that you require.