Created
November 28, 2019 08:21
-
-
Save mwyrebski/586880bbe7e64783a924e5ab307aab4f to your computer and use it in GitHub Desktop.
Enumerating through Cases of Discriminated Union in F#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // 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