C#中的通用Map/Reduce List Extensions

Ben*_*iel 26 c# extension-methods functional-programming

我正在编写一些扩展来模仿地图并减少Lisp中的函数.

public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);

public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
     var aggregate = initial;
     foreach(var t in list)
         aggregate = r(t,aggregate);

     return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
    foreach(var t in list)
         f(t,args);
}
Run Code Online (Sandbox Code Playgroud)

转换功能将减少如下:

foreach(var t in list)
    if(conditions && moreconditions)
        //do work etc
Run Code Online (Sandbox Code Playgroud)

这有意义吗?会更好吗?

Ray*_*ega 50

根据这个链接C#3.0中的函数编程:Map/Reduce/Filter如何可以摇滚你的世界以下是System.Linq命名空间中C#的等价物:


Kei*_*ith 35

这些看起来非常类似于Linq中的扩展:

//takes a function that matches the Func<T,R> delegate
listInstance.Aggregate( 
    startingValue, 
    (x, y) => /* aggregate two subsequent values */ );

//takes a function that matches the Action<T> delegate
listInstance.ForEach( 
    x => /* do something with x */);
Run Code Online (Sandbox Code Playgroud)

为什么第二个例子叫做Transform?你打算以某种方式更改列表中的值吗?如果是这种情况你可能最好使用ConvertAll<T>Select<T>.