Hi, the difficulty with List.Cons is that it is not a value, but a static member (it seems to be the same for a usual function, but not for a generic value like List.empty). This means that the F# compiler cannot treat it as a "Call" without any arguments and it adds lambda function around it like this:

1
2
3
4
5
 
Instead of:
<@@ List.Cons @@>
You'll get:
<@@ fun hd tl -> List.Cons(hd, tl) @@>

However, this is a problem, because quotations cannot be generic, so the F# compiler uses the default type, which is "obj" and so the type of the lambda function actually becomes: obj -> obj list -> obj list. This means that we can't simply extract the call and just change the type parameter. If you know the type statically, then you can just simply write the following:

1
2
3
4
5
 
let make_cons<'t> = 
  <@@ List.Cons : 't * _ -> _ @@>

let consInt = make_cons<int> // for example

If you need to do this dynamically, then you can construct the call to List.Cons by hand using reflection. As you mentioned, the "Cons" method isn't generic, because it is actually List<'a>.Cons, so we have to construct the generic type first:

1
2
3
4
5
6
7
let generic_list = typeof<List<obj>>.GetGenericTypeDefinition()
let make_list_cons t args =
    Expr.Call(generic_list.MakeGenericType([| t |]).GetMethod("Cons"), args)
  
// for example:  
let sample = 
    make_list_cons (typeof<int>) [ <@@ 1 @@>; <@@ [] : list<int> @@> ]

Hope this helps!
T.

By on 10/8/2008 2:45 AM ()

Excellent, that's done the trick. Thanks a lot, Tomas!

By on 10/9/2008 10:09 AM ()

One remaining question on this topic:

How do I take something of type Expr (i.e., an untyped expression), and promote it to something of type Expr<'a>?

The reason I ask is that I have some programmatically generated raw expression, and I'd like to splice it into a quotation using "%", e.g.:

let x_untyped : Expr = .......
let x_typed : Expr<float> = ???? x_untyped
let y = <@@ %x_typed + 1. @@>

By on 10/13/2008 8:56 AM ()

(bump)

By on 10/19/2008 5:00 AM ()

Try Expr.Cast.
Cheers!
don

By on 10/19/2008 9:59 AM ()

Didn't see it hiding there, thanks Don!

By on 10/19/2008 2:58 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