开发者

Randomly choose an instance from union in F#

开发者 https://www.devze.com 2022-12-13 04:25 出处:网络
In F#, given type MyType = A | B | C |开发者_运维问答 D | E | F | G How do I randomly define an instance of MyType?This ought to work:

In F#, given

type MyType = A | B | C |开发者_运维问答 D | E | F | G

How do I randomly define an instance of MyType?


This ought to work:

let randInst<'t>() = 
  let cases = Reflection.FSharpType.GetUnionCases(typeof<'t>)
  let index = System.Random().Next(cases.Length)
  let case = cases.[index]
  Reflection.FSharpValue.MakeUnion(case, [||]) :?> 't

This code assumes that the union cases are all nullary and that the type you're using is actually a union type, but it would be easy to explicitly check those assumptions and throw meaningful exceptions if desired.


Select a random number, then pattern match that number with different branches returning a different instant?

0

精彩评论

暂无评论...
验证码 换一张
取 消