Skip to content

Instantly share code, notes, and snippets.

@kekyo
Last active June 1, 2016 06:40
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 kekyo/2ebce0a74977e0bd2b5939fb2bde257a to your computer and use it in GitHub Desktop.
Save kekyo/2ebce0a74977e0bd2b5939fb2bde257a to your computer and use it in GitHub Desktop.
Dump target instance recursivity in F# (partial code).
// TODO: Discriminated Unions
let (|Null|Primitive|String|Enumerable|Complex|) (target: obj) =
match target with
| null -> Null
| _ ->
let targetType = target.GetType()
match targetType.IsPrimitive || targetType.IsEnum with
| true -> Primitive(targetType)
| false ->
match targetType = typeof<System.String> with
| true -> String(target :?> System.String)
| false ->
match typeof<System.Collections.IEnumerable>.IsAssignableFrom targetType with
| true -> Enumerable(target :?> System.Collections.IEnumerable |> Seq.cast<obj>)
| false -> Complex(targetType)
let rec dumper target name indent =
match target with
| Null -> seq {
yield System.String.Format("{0}{1} = null", indent, name)
}
| Primitive _ -> seq {
yield System.String.Format("{0}{1} = {2}", indent, name, target)
}
| String str -> seq {
yield System.String.Format("{0}{1} = \"{2}\"", indent, name, str)
}
| Enumerable en -> seq {
yield System.String.Format("{0}{1} = [", indent, name)
let childIndent = indent + " "
let mutable index = 0
for child in en do
yield! dumper child (System.String.Format("[{0}]", index)) childIndent
index <- index + 1
yield System.String.Format("{0}]", indent)
}
| Complex targetType -> seq {
yield System.String.Format("{0}{1} = {{", indent, name)
let pis = targetType.GetProperties(BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.DeclaredOnly)
let filter (pi: PropertyInfo) =
let getter = pi.GetMethod
let indexers = pi.GetIndexParameters()
pi.CanRead && (indexers.Length = 0) && (getter <> null) && (not getter.IsPrivate)
let fpis = pis |> Seq.filter filter |> Seq.sortBy (fun pi -> pi.Name) |> Seq.toArray
let childIndent = indent + " "
for pi in fpis do
let child = pi.GetValue(target, null)
yield! dumper child pi.Name childIndent
yield System.String.Format("{0}}}", indent)
}
let dump =
System.String.Join(
"\r\n",
dumper tcConfigB "tcConfigB" "")
do Console.WriteLine(dump)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment