How to transfer an F # function to another F # function from a C # application?

I have an assembly of the F # class library, which contains two functions:

let add a b = a + b

and

let rec aggregateList list init (op:int -> int -> int) =
    match list with
    |[] -> init
    |head::tail ->
        let rest = aggregateList tail init op
        op rest head

I have a C # console application that references the F # library and tries to do the following:

FSharpList<int> l = new FSharpList<int>(1, new FSharpList<int>(2, FSharpList<int>.Empty));
int result = myFsLibrary.aggregateList(l, 0, myFsLibrary.add);

However, the compiler complains that [myFsLibrary.add] cannot be converted from a "method group" to FSharpFunc<int, FSharpFunc<int, int>>

+3
source share
3 answers

You can explicitly create a function using a delegate FSharpFunc. In C #, it’s more convenient to create a function that takes all arguments as a tuple, so you can do this and then convert the function to curry with FuncConvert. Sort of:

FuncConvert.FuncFromTupled(new FSharpFunc<Tuple<int, int>, int>(args => 
    arags.Item1 + args.Item2))

, F # #, #. Func, IEnumerable F #:

module List = 
    let AggregateListFriendly inp init (op:Func<int, int, int>) =
        aggregateList (List.ofSeq inp) init (fun a b -> op.Invoke(a, b))

# :

List.AggregateListFriendly(Enumerable.Range(0, 10), 0, (a, b) => a + b));
+5

, .Net

int add(int, int)

# .Net-, . , 2 int int. F #, . add, int , int int. , currying.

# F #, , . , F # factory , .

[<Extension>]
type public FSharpFuncUtil = 

    [<Extension>] 
    static member ToFSharpFunc<'a,'b,'c> (func:System.Func<'a,'b,'c>) = 
        fun x y -> func.Invoke(x,y)

    static member Create<'a,'b,'c> (func:System.Func<'a,'b,'c>) = 
        FSharpFuncUtil.ToFSharpFunc func

, F # add, :

var del = FSharpFuncUtil.Create<int, int, int>(myFsLibrary.add);
0

All Articles