Skip to content

Instantly share code, notes, and snippets.

@Szer
Last active December 17, 2019 17:16
Show Gist options
  • Save Szer/bf9cb8dd3c446859a949196b4d9c52fc to your computer and use it in GitHub Desktop.
Save Szer/bf9cb8dd3c446859a949196b4d9c52fc to your computer and use it in GitHub Desktop.
Pretty printing DU recursively
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