Created
June 19, 2021 05:13
-
-
Save bmitc/c3bf27dbff8fe057db16dfaa2a71d28f to your computer and use it in GitHub Desktop.
Convert discriminated union values to and from strings
This file contains 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
open Microsoft.FSharp.Reflection | |
let toString (x: 'T) = | |
match FSharpValue.GetUnionFields(x, typeof<'T>) with | |
| case, _ -> case.Name | |
let fromString<'T> (s: string) = | |
match FSharpType.GetUnionCases typeof<'T> |> Array.filter (fun case -> case.Name = s) with | |
| [|case|] -> Some(FSharpValue.MakeUnion(case, [||]) :?> 'T) | |
| _ -> None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment