F #: Can units be linked dynamically at runtime?

I am very new to F # and intrigued by the Units of Measure functionality and have a general idea of ​​how it works normally, but I would like to know if it is possible to bind measures to values ​​where we do not know what the measure will be until the code won't fulfill?

The practical example I'm looking at is mandatory floats as currency values, where the unit of measure is inferred from the database search.

Suppose that measures for each currency (USD, EUR, AUD, etc.) are usually announced:

[<Measure>] USD
[<Measure>] EUR
[<Measure>] AUD
...

First you need a way to get the type of measure from the identifier, ideally the name of the measure itself, since the currency code is most likely stored and retrieved as a 3-character string (similar Enum.Parse()).

Then you need a way to bind the float value to the type created in the previous step.

Is this possible, or is there another way to achieve the same result?

+4
source share
2 answers

This is not possible since the units of measure F # are erased (they exist only at compile time).

You can create a library with runtime implementations (I did not think about how the design would look). But you are likely to lose static validation.

I think that perhaps the best strategy might be to select the border, and at the boundary point (where you read from the database and derive unit types) somehow get the correct types in the type system, but depending on how the code is structured and what exactly are you doing, which may or may not be / easy ...

+4

, , , , AUD .. /.

, . , , ( ) , , float<'a> -> float<'a> , : , , , .

+1

All Articles