Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interop between F# and C# lambdas

Tags:

lambda

interop

f#

F# powerpack comes with a set of conversion methods to translate from Func<...> to F# functions, either standard or tupled ones. But is it possible to achieve the opposite: in case you want to call from F# code a C# method that takes Func<...> and want to use native F# lambda expression (e.g. fun x -> some_function_of(x))?

If I send a F# function with a signature 'a -> 'b to a C# method that expects Func then F# compiler generates the following error:

This expression was expected to have type Function<'T,'R> but here has type 'T -> 'R

I want to stay with F# lambda expressions but to use a translation layer in order to be able to send them as C# Func lambda. Is this achievable?

like image 823
Vagif Abilov Avatar asked Aug 02 '10 21:08

Vagif Abilov


1 Answers

F# provides constructors for all delegate types that take F# values of the corresponding function types. E.g. in your case you want to use System.Func<_,_>(fun x -> ...) which applies the generated constructor of type ('a -> 'b) -> System.Func<'a, 'b>.

like image 157
kvb Avatar answered Sep 30 '22 12:09

kvb