Creating a list with multiple units of measure for floats in F #

So, I tried to get around this in various ways, but I just can't do this work.

Is there a way to make a list containing the values ​​of different units (all based on floats)? For instance:

let myList = [0.07<ms>; 0.9; 7.2<mm>;] 

Since they are considered as different types, you cannot put them on the same list. I tried declaring the list as let myList : float<_> list = ... and gave dimensionless numbers a unit, but I still had an input error: I expected float <'u>, but got a float.

I can not use tuple / n-ple, because I do not know the number of values ​​that will be in the list.

I am new to F # and spent a lot of time cleaning up documents and web storage, but could not find a solution. If anyone could point me in the right direction, I would really appreciate it. Thanks!

+1
source share
2 answers

I think you need to provide a longer example showing how you want to use this list. Otherwise, it is difficult to give a good answer, because it depends on the use.

If you just want to create a list of numbers representing different things, then you can use the discriminated union to distinguish between them:

 type Numeric = | Length of float<mm> | Time of float<ms> | Unitless of float let myList = [ Time 0.07<ms>; Unitless 0.9; Length 7.2<mm>;] 

Then you can create a list containing different numbers (with different physical values). When repeating through a list, you will need to use pattern matching to retrieve the value.

Alternatively, you can simply discard all units when creating the list, but then you lose the guarantees provided by the units (this means that when you get some value from the list, you will not know what the unit is, and you may interpret it incorrectly):

 let myList = [ float 0.07<ms>; 0.9; float 7.2<mm>;] 

You can also use the F # library, which allows you to track devices at runtime .

+4
source

All list members must be of the same type . A float<ms> does not match float<mm> .

+1
source

All Articles