Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly choose an instance from union in F#

Tags:

union

f#

In F#, given

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

How do I randomly define an instance of MyType?

like image 280
sthiers Avatar asked Dec 06 '09 11:12

sthiers


1 Answers

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.

like image 116
kvb Avatar answered Sep 30 '22 21:09

kvb