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();

Source

+3
source share
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

-, CLR (LINQ). ( , , ):

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

F # [1], :

/// Convert F# quotations to LINQ expression trees.
/// A more polished LINQ-Quotation translator will be published
/// concert with later versions of LINQ.
let rec ConvExpr env (inp:Expr) = ...
  • .../FSharp-1.9.6.2//FSharp/FSharp.PowerPack.Linq/Linq.fs

F # [2,3].

  1. http://msdn.microsoft.com/en-us/library/dd233212(VS.100).aspx
  2. http://tomasp.net/blog/fsharp-quotation-samples.aspx
+2

Source: https://habr.com/ru/post/1727007/


All Articles