Skip to content

Instantly share code, notes, and snippets.

@lessismore1
Created March 25, 2018 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lessismore1/d729c03ac43267d82db74c8fcff4e4a0 to your computer and use it in GitHub Desktop.
Save lessismore1/d729c03ac43267d82db74c8fcff4e4a0 to your computer and use it in GitHub Desktop.
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