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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With