Created
March 25, 2018 20:31
-
-
Save lessismore1/d729c03ac43267d82db74c8fcff4e4a0 to your computer and use it in GitHub Desktop.
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
open Microsoft.FSharp.Reflection | |
let toString (x:'a) = | |
match FSharpValue.GetUnionFields(x, typeof<'a>) with | |
| case, _ -> case.Name | |
let fromString<'a> (s:string) = | |
match FSharpType.GetUnionCases typeof<'a> |> Array.filter (fun case -> case.Name = s) with | |
|[|case|] -> Some(FSharpValue.MakeUnion(case,[||]) :?> 'a) | |
|_ -> None | |
// Usage: | |
// type A = X|Y|Z with | |
// member this.toString = toString this | |
// static member fromString s = fromString<A> s | |
// > X.toString;; | |
// val it : string = "X" | |
// > A.fromString "X";; | |
// val it : A option = Some X | |
// > A.fromString "W";; | |
// val it : A option = None | |
// > toString X;; | |
// val it : string = "X" | |
// > fromString<A> "X";; | |
// val it : A option = Some X |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment