Using C # delegates with f # functions

I am trying to call a C # function from f # where the C # function takes a function (delegate?) As a parameter, and I need this argument as a f # function. For instance:

C # example

public static void function_1(double x, ref double y) { y = Math.Exp(x); } main() { state s; call_func(s, function_1) } 

So call_func has a parameter of type void fn(double, ref double)

In f #, I tried:

 let function_1 (x:double) (y:double byref) = let y = 6.0 () let test = let s = new state let ret = call_func(s, function_1) 

But I get the error that f # function_1 is of type double -> double byref -> unit when it should be the delegate type void fn(double, ref double) .

Is it possible to use a type or something like that? Or is there a mistake?

+6
source share
1 answer

If you want to create a delegate from a function in F #, you can use the new operator and give it a function as an argument:

 let function_1 (x:double) (y:double) = () Program.call_func(s, new Action<double, double>(function_1)) 

But for some reason , if you try to use the same approach with the delegate that contains ref , you get this error:

This function value is used to construct a delegate type whose signature includes the byref argument. You must use an explicit lambda expression with two arguments.

So, if you follow the recommendations given in the error message, you can write the following:

 let function_1 (x:double) (y:double byref) = y <- 6.0 Program.call_func(s, new fn(fun x -> fun y -> function_1 x &y)) 

This compiles and works as expected.

Note that to change the y parameter y you need to use the <- operator. Using let y = 6.0 declares a completely different variable that obscures the parameter.

+9
source

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


All Articles