ebb
ebb

Reputation: 9397

F# - Create Expr by hand

I'm trying to create a Expr<'a -> string by hand, and after several hours reading and trying I give up..

However, I did figure out how to write the C# version:

let buildExpression<'a> =
    let p = E.Parameter(typeof<'a>)
    E.Lambda<F<'a,string>>(p)

which will produce:

Expression<Func<'a, string>>

So my question is, how do I create a Expr<'a -> string> by using the Expr module?

Upvotes: 1

Views: 466

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243126

The C# sample is a bit suspicious, if you called buildExpression<int>, then the result would be an expression (in the C# sytnax): Func<int, string>(x => x), which has a wrong type. I guess C# doesn't check types at construction time, but if you tried compiling it, it would probably crash.

I guess you want to build something like x => x.Foo. Then the following snippet should do the trick:

open Microsoft.FSharp.Quotations

type Foo() =
  member x.Prop = "hello"

// Create a new variable 'x'
let arg = Var.Global("x", typeof<Foo>)
// Use Reflection to get information about the 'Prop' member
let propInfo = typeof<Foo>.GetProperty("Prop")
// Create a lambda 'fun x -> x.Prop'
let e = Expr.Lambda(arg, Expr.PropertyGet(Expr.Var(arg), propInfo))

Upvotes: 2

Related Questions