tags:

views:

119

answers:

2

In F#, given

type MyType = A | B | C | D | E | F | G

How do I randomly define an instance of MyType?

+5  A: 

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

Richard
I thought F# might have a built-in way of listing these union constructors, like Bounded and Enum in Haskell, but apparently not.
Tim Robinson
+6  A: 

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.

kvb