문제

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!

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top