How to call a C # method, taking a parameter of type Expression <T> from F #?
I am trying to use the Brahma library from F #, and I need to call a method that takes an Exprssion parameter as a parameter, and I don't know how to do it.
here is the C # code that I would like to translate:
// Create the computation provider
var computationProvider = new ComputationProvider();
// Create a data-parallel array and fill it with data
var data = new DataParallelArray<float>(computationProvider,
new[] { 0f, 1f, 2f, 3f, 4f, 5f, 6f });
// Compile the query
CompiledQuery query = computationProvider.Compile<DataParallelArray<float>>
(
d => from value in d
select value * 2f
);
// Run the query on this data
IQueryable result = computationProvider.Run(query, data);
// Print out the results
foreach (float value in result)
Console.WriteLine(result[i]);
// Get rid of all the stuff we created
computationProvider.Dispose();
data.Dispose();
result.Dispose();
+3
2 answers
You need to use F # quotes, but they create F # expression (Expr) objects, and translating into CLR expressions is a bit difficult.
Start by writing the expression as quotes from F #:
let expr = <@ fun (d : DataParallelArray<float>) -> d.ToString() @> // real implementation omitted
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
open System.Linq.Expressions
let ToLinq (exp : Expr<'a -> 'b>) =
let linq = exp.ToLinqExpression()
let call = linq :?> MethodCallExpression
let lambda = call.Arguments.[0] :?> LambdaExpression
Expression.Lambda<Func<'a, 'b>>(lambda.Body, lambda.Parameters)
( , F # PowerPack, PowerPack ToLinqExpression , .)
ToLinq F # :
let clrExpression = expr |> ToLinq
// pass clrExpression to Compile method
( , , .)
+3