Last active
December 17, 2019 17:16
-
-
Save Szer/bf9cb8dd3c446859a949196b4d9c52fc to your computer and use it in GitHub Desktop.
Pretty printing DU recursively
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 System.Text | |
open Microsoft.FSharp.Reflection | |
let printDu du = | |
let rec inner (builder: StringBuilder, duValue: obj, duType: Type) = | |
if not (FSharpType.IsUnion duType) then failwith "FU!" | |
let case, values = FSharpValue.GetUnionFields(duValue, duType) | |
if values.Length > 1 then failwith "FU!" | |
let value = values.[0] | |
let valueType = value.GetType() | |
builder.Append case.Name |> ignore | |
if FSharpType.IsUnion valueType then | |
builder.Append(" -> ") |> ignore | |
inner (builder, value, valueType) | |
else | |
builder.Append (" " + value.ToString()) |> ignore | |
builder.ToString() | |
inner (StringBuilder(), du, du.GetType()) | |
printDu (Some (Ok 1)) //"Some -> Ok 1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment