Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 630
bradgonesurfing Avatar asked Mar 10 '13 13:03

bradgonesurfing


1 Answers

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

like image 173
Tomas Petricek Avatar answered Oct 15 '22 11:10

Tomas Petricek