How can I enumerate through the possible "values" of a discriminated union in F#?
I want to know if is there something like Enum.GetValues(Type)
for discriminated unions, tough I am not sure over what kind of data I would enumerate. I would like to generate a list or array of a discriminated union with one item for each option.
Yes, F# has it's own reflection layer build on top of .NET's reflection to help you make sense of types that are specific to F#, like discriminating unions. Here's the code that will let you enumerate a union's cases:
It's hard to see how this could possibly work without also having an instance since discrimination unions can carry values.
If you had a type like this for example:
What would you except your array to contain for Success or Error in this case?
If your discriminated union is only made of plain identifiers (no case storing any data, this might be what you need: gist
To slightly extend Robert's example - even if you don't have an instance of the discriminated union, you can use F# reflection to get the information about the type (such as types of the arguments of individual cases). The following extends Robert's sample ans it also prints the types of arguments:
For example, for
option<int>
type, you'll get (I slightly simplified the output):There are many interesting uses for this information - for example, you could generate DB schema from F# unions or to create functions that will parse XML into a discriminated union (that describes the structure). I talked about the XML processing sample at GOTO conference earlier this year.