Skip to content

Instantly share code, notes, and snippets.

@acgetchell
Last active August 8, 2016 22:51
Show Gist options
  • Save acgetchell/926997 to your computer and use it in GitHub Desktop.
Save acgetchell/926997 to your computer and use it in GitHub Desktop.
Uses reflection provided by F# in the FSharpType namespace to translate a given System.Type object into a value of the 'a ty union type defined by https://gist.github.com/926994. From Jon Harrop's "Visual F# 2010 for Technical Computing"
let rec type_of f = function
| ty when Reflection.FSharpType.IsFunction ty ->
let ty_arg, ty_ret = Reflection.FSharpType.GetFunctionElements ty
Function(type_of f ty_arg, type_of f ty_ret)
| ty when Reflection.FSharpType.IsTuple ty ->
Tuple
[ for ty in Reflection.FSharpType.GetTupleElements ty do
yield type_of f ty ]
| ty when Reflection.FSharpType.IsRecord ty ->
Record( ty.Name,
[ for pi in Reflection.FSharpType.GetRecordFields ty do
for acc in pi.GetAccessors() do
yield pi.Name, f acc.ReturnType ] )
| ty when Reflection.FSharpType.IsUnion ty ->
Union( ty.Name,
[ for uc in Reflection.FSharpType.GetUnionCases ty do
let args =
[ for field in uc.GetFields() ->
f field.PropertyType ]
yield uc.Name, args ])
| ty ->
Abbrev( [ for ty in ty.GetGenericArguments() -> f ty ],
ty.FullName);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment