Matching Unit Templates in F #

This function:

let convert (v: float<_>) =
  match v with
  | :? float<m> -> v / 0.1<m>
  | :? float<m/s> -> v / 0.2<m/s>
  | _ -> failwith "unknown"

causes an error

The type 'float <' u> 'does not have the proper subtypes and cannot be used as a source for a type or runtime test.

Is there a way to account for the coincidence of units?

+3
source share
3 answers

As @kvb explains, the problem is that units are part of the type. This means that it float<m>is different from float<m/s>(and, unfortunately, this information is not stored as part of the value at run time).

, , . , , :

type SomeValue = 
  | M of float<m>
  | MPS of float<m/s>

, :

let convert v = 
  match v with 
  | M v -> v / 0.1<m>
  | MPS v -> v / 0.2<m/s>

, , , ( - ).

, int float, ( F #), , F # .

+6

. , , , , :

let convert (v: float<'u>) = //'
  match v with
  | :? float<m> -> v / 0.1<m>
  | :? float<m/s> -> v / 0.2<m/s>
  | _ -> failwith "unknown"

, , v float<'u>, float<'u> , , , t24 > .

v . , , list<'a> , list<int>, , ( , , , Java). , F # , - , float - F # , Java .

, , , - , , ; . ? , , , , F #.

+3

. " " http://msdn.microsoft.com/en-us/library/dd233243.aspx.

@kvb, , - .

, :

let convert (v: float<_>) =
  match v with
  | :? float<m> -> v<m>
  | :? float<inches> -> v * 2.54 / 100.0<m>
0

Source: https://habr.com/ru/post/1741746/


All Articles