bradgonesurfing
bradgonesurfing

Reputation: 32192

What is the most up to date way to compile code quotations in F#

I'm building a symbolic derivative engine. For example

let f = <@ fun x:double -> x * x @>
let df = der f

and the resulting expression will be

<@ 2 * x @>

The actual equations could be arbitrarily complex.

The generation of the derivatives are not too hard using recursive pattern matching and transformations but in the end I want to use the generated equations in tight numerical loops as if I had hand written them. This is numerical computing code so faster is always better ( if possible )

I've looked at the FSharpX quotation compiler but it looks like an interpreter rather than a compiler.

Upvotes: 7

Views: 445

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243061

I have not tested this, but the code that translates F# quotations to LINQ expressions (and compiles them) has now moved from F# PowerPack into the F# Core library, so I think that is the most up-to-date version:

open Microsoft.FSharp.Linq.RuntimeHelpers

LeafExpressionConverter.EvaluateQuotation <@ 1 + 2 @>

and to use it for lambdas

let d=LeafExpressionConverter.EvaluateQuotation <@ fun y -> y+1.0 @> 
    :?> ( double -> double )

Console.WriteLine(d 10)

outputs

11

Note the cast at the end to convert the ''obj'' to a lambda of the correct type

Upvotes: 7

Related Questions