Skip to content

Instantly share code, notes, and snippets.

@mwyrebski
Created November 28, 2019 08:21
Show Gist options
  • Select an option

  • Save mwyrebski/586880bbe7e64783a924e5ab307aab4f to your computer and use it in GitHub Desktop.

Select an option

Save mwyrebski/586880bbe7e64783a924e5ab307aab4f to your computer and use it in GitHub Desktop.
Enumerating through Cases of Discriminated Union in F#
//
// Example of enumerating through Cases of Discriminated Unions.
//
type Rgb =
| R
| G
| B
let colorText c =
match c with
| R -> "Red"
| G -> "Green"
| B -> "Blue"
open Microsoft.FSharp.Reflection
let unionCases<'a> = FSharpType.GetUnionCases typeof<'a>
let createUnion<'a> case = FSharpValue.MakeUnion(case, Array.empty) :?> 'a
let allTexts = unionCases<Rgb>
|> Array.map createUnion<Rgb>
|> Array.map colorText
let containsColor value =
allTexts
|> Array.contains value
// ----------------------------------------------
colorText R // "Red"
colorText G // "Green"
colorText B // "Blue"
containsColor "Green" // true
containsColor "Black" // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment