c#调用F#中的lambda表达式

c#调用F#自定义的库,可能会经常遇到F#函数采用了Lambda作为函数参数,在C#中lambda参数被生成了FSharpFunc<T1, TResult>>> 对象,不能直接用C#中的lambda表达式作为实参来调用,我们只有通过把lambda表达式转换为FSharpFunc<T1, TResult>>> 对象,以下就是把lambd表达式转换为FSharpFunc对象的方法:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FSharp.Core;
namespace XZL.FSharpHelp
{
    public class FuncToFSharpFunc
    {
        public static FSharpFunc<T1, TResult> Create<T1, TResult>(Func<T1, TResult> func)
        {
            Converter<T1, TResult> conv = value1 => func(value1);
            return FSharpFunc<T1, TResult>.FromConverter(conv);
        }
        public static FSharpFunc<T1, FSharpFunc<T2, TResult>> Create<T1, T2, TResult>(Func<T1, T2, TResult> func)
        {
            Converter<T1, FSharpFunc<T2, TResult>> conv = value1 =>
            {
                return Create<T2, TResult>(value2 => func(value1, value2));
            };
            return FSharpFunc<T1, FSharpFunc<T2, TResult>>.FromConverter(conv);
        }
        public static FSharpFunc<T1, FSharpFunc<T2, FSharpFunc<T3, TResult>>> Create<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> func)
        {
            Converter<T1, FSharpFunc<T2, FSharpFunc<T3, TResult>>> conv = value1 =>
                {
                    return Create<T2, T3, TResult>((value2, value3) => func(value1, value2, value3));
                };
            return FSharpFunc<T1, FSharpFunc<T2, FSharpFunc<T3, TResult>>>.FromConverter(conv);
        }
    }
}

  下面我举例说明用法:

  首先用F#定义一个以lambda参数作为函数如下:

 let Random(row:int) (col:int) f = Array2D.init row col f

  在C#中调用这个F#函数参数一个随机二维数组:

1 Random r = new Random();
2 Func<int, int, double> func = (i, j) => r.NextDouble();
3 var f = FuncToFSharpFunc.Create<int, int, double>(func);
4 double[,] c = MatrixMod.Random<double>(4, 4, f);

  

posted on 2011-08-26 21:31  小指令  阅读(2273)  评论(0编辑  收藏  举报

导航