Creating a list with multiple units of measurements of floats in F#

流过昼夜 提交于 2019-12-11 05:50:27

问题


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

Is there any way to make a list that contains values of varying units of measurement (all based on floats)? For example:

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

As they are treated as different types, you cannot put them in the same list. I tried declaring the list as let myList : float<_> list = ..., and giving dimensionless numbers a unit of measurement, but I still got a typing error: expecting float<'u> but got float.

I am unable to use a tuple/n-ple as I do not know the number of values that will be in the list.

I am quite new to F# and have spent quite a while scouring the documents and web on storage, but haven't found a solution. If anyone could point me in the right direction, I would really appreciate it. Thank you!


回答1:


I think you'll need to give a longer example that shows 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 that represent different things, then you can consider using a discriminated union to differentiate 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 that contains different numbers (with different physical meanings). When iterating over the list, you'll need to use pattern matching to extract the value.

Alternatively, you can just drop all units when creating the list, but then you lose the guarantees provided by units of measure (meaning that when you get some value from the list, you won't know what unit it had and you could interpret it wrongly):

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

You could also use an F# library that lets you track units at runtime.




回答2:


All members of a list must have the same type. A float<ms> is not the same as a float<mm>.



来源:https://stackoverflow.com/questions/13567081/creating-a-list-with-multiple-units-of-measurements-of-floats-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!