How to Convert Expr<'a -> 'b> to Expression>

前端 未结 1 1016
滥情空心
滥情空心 2021-02-10 03:50

I\'m using F# 3.0 with .NET 4.5 beta, and I\'m trying to convert an F# quotation of type Expr<\'a -> \'b> to a LINQ Expression

相关标签:
1条回答
  • 2021-02-10 04:49

    Can you post a more complete sample and also include the F# expression that you're trying to convert?

    I tried to test the behaviour on .NET 4.5 using a minimal sample and it worked for me. Here is what I did:

    • I created new F# 3.0 project and copied Linq.fs and Linq.fsi from the 2.0 version of F# PowerPack. (Or is there a 3.0 version of the ToLinqExpression method available somewhere in F# 3.0?)

    • I used the code from Daniel's earlier answer and called the function as follows:

      let r = toLinq <@ fun x -> x + 1 @>
      printfn "%A" r
      

      This did not throw any exception and it printed x => (x + 1), which looks correct to me.

    EDIT: To answer the updated question - both of the code samples that you referred to (mine and Daniel's) assume that the body of the quotation is an explicitly constructed function, so they only work on quotations of a specific structure: <@ fun x -> ... @>.

    You can fix the problem by using splicing in an explicitly constructed function. The following works for me:

    let exp = <@ fun x -> x + 1 @> 
    let r = toLinq <@ fun a -> box ((%exp) a) @> 
    printfn "%A" r
    

    This contains application of an F# function, so the generated Expression contains a call to ToFSharpFunc (which converts a delegate to an F# function) and then invocation of this. This may be an issue if you want Expression that standard .NET tools can understand (in which case, you'd have to post-process the C# expression tree and remove these constructs).

    0 讨论(0)
提交回复
热议问题