You created a runtime list<obj> but you need a list<MyType>. Here's some code that is suggestive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 

type MyType = | One of string | Lots of MyType list 

open Microsoft.FSharp.Reflection
open System.Reflection

let ty = typeof<MyType>
let [|one; lots|] = FSharpType.GetUnionCases ty
let oneVal = FSharpValue.MakeUnion(one, [|box "foo"|])

printfn "%A" oneVal

let listTyGen = typedefof<list<_>>
let listTy = listTyGen.MakeGenericType [| ty |]
let emptyListOfTy = listTy.GetProperty("Empty", BindingFlags.Static ||| BindingFlags.Public).GetValue(null, [||])
let oneElListOfTy = listTy.GetMethod("Cons", BindingFlags.Static ||| BindingFlags.Public).Invoke(null, [|oneVal;emptyListOfTy|])
let lotsVal = FSharpValue.MakeUnion(lots, [|oneElListOfTy|])

printfn "%A" lotsVal

By on 11/22/2009 1:38 PM ()

Thanks for the secret sauce! (I'd love to see this example in the MakeUnion docs...)

Can't the list case be covarient with the single value initalizer? -- seems weird that I can pass in the obj (rather than a MyType) but not the obj list (rather than the MyType list.)

If I already have the List<obj>, is there a way to get the List<t> all at once (like a Seq.cast<T>.ToList(), but where T is known at runtime), or do I need to invoke cons recursively myself?

[Geez, even in a code block I can't keep &gt's and &lt's??]

thanks again

By on 11/22/2009 6:52 PM ()

More code:

1
2
3
4
5
6
7
8
9
let ol : obj list = [ oneVal; oneVal ]
let seqModule = typeof<list<int>>.Assembly.GetType("Microsoft.FSharp.Collections.SeqModule")
let castMethod = seqModule.GetMethod("Cast", BindingFlags.Static ||| BindingFlags.Public)
let castMethodMyTy = castMethod.MakeGenericMethod [| ty |]
let seqMyTy = castMethodMyTy.Invoke(null, [| ol |])
let listMyTy = seqModule.GetMethod("ToList", BindingFlags.Static ||| BindingFlags.Public)
                .MakeGenericMethod( [| ty |] )
                .Invoke(null, [| seqMyTy |])
printfn "%A" listMyTy
By on 11/22/2009 11:09 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper