How to write a function where the argument is a type but not a typed value?

I want to convert string representations from dozens of enumeration types to enumeration values. It is easy to convert a string to a specific type:

Enum.Parse(typeof<FontStyle>,"Bold") |> unbox<FontStyle>

but for now I want to write a function where type and string are parameters. The best I can write is:

> let s2e (_: 'a) s = Enum.Parse(typeof<'a>,s) |> unbox<'a>;;
val s2e : 'a -> string -> 'a
> s2e FontStyle.Regular "Bold";;
val it : FontStyle = Bold

Is there a way to write something like this, but with the type itself as the first argument?

+3
source share
2 answers

, . "" , - , defaultof<SomeType>,

, ( SO, "" ):

> let parseEnum<´a> s = Enum.Parse(typeof<´a>,s) |> unbox<´a>;; 
val parseEnum : string -> ´a

:

> parseEnum<FontStyle> "Bold";; 
val it : FontStyle = Bold

- , , .

+4

. , , F # enum :

let parseEnum<'t,'u when 't:enum<'u>> s = System.Enum.Parse(typeof<'t>, s) :?> 't
(parseEnum "Class" : System.AttributeTargets)

(parseEnum "Test" : int) , int .

'u, F #, ssp . , :

let parseEnum<'t when 't :> System.Enum and 't : struct> s =
  System.Enum.Parse(typeof<'t>, s) :?> 't

, struct System.Enum .

+1

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


All Articles