Randomly choose an instance from union in F#
Question
In F#, given
type MyType = A | B | C | D | E | F | G
How do I randomly define an instance of MyType?
Solution
Select a random number, then pattern match that number with different branches returning a different instant?
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow