Mapa genérico/Reduzir a Lista de Extensões em C#
-
09-06-2019 - |
Pergunta
Estou escrevendo algumas extensões para imitar o mapa e reduzir funções em 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);
}
A função de transformação irá reduzir cruft como:
foreach(var t in list)
if(conditions && moreconditions)
//do work etc
Isto faz sentido?Poderia ser melhor?
Solução
Estas são muito semelhantes para as extensões de Linq já:
//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 */);
Qual é o 2º exemplo chamado de Transformação?Você pretende alterar os valores na lista de alguma forma?Se for esse o caso, você pode ser melhor fora de usar ConvertAll<T>
ou Select<T>
.
Outras dicas
De acordo com este link Programação funcional em C# 3.0:Como Mapear/Reduzir/Filtro pode agitar o seu Mundo a seguir são equivalentes em C# no âmbito do Sistema.Linq espaço de nomes:
- mapa --> Enumeráveis.Selecione
- reduzir --> Enumeráveis.Agregados
- filtro --> Enumeráveis.Onde
Eu gostaria de usar o construída em Func delegados em vez disso.Este mesmo código funciona em qualquer IEnumerable.O código iria se transformar em:
public static R Reduce<T,R>(this IEnumerable<T> list, Func<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 IEnumerable<T> list, Func<T> f)
{
foreach(var t in list)
f(t);
}
Você pode querer adicionar uma maneira de fazer um mapa, mas o retorno de uma nova lista, em vez de trabalhar em lista aprovada em (e retornar a lista pode ser útil para a cadeia de outras operações)...talvez uma versão sobrecarregada com um booleano que indica se você deseja retornar a uma nova lista ou não, tais como:
public static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,
params object [] args)
{
return Transform(list, f, false, args);
}
public static List<T> Transform<T>(this List<T> list, TransformFunction<T> f,
bool create, params object [] args)
{
// Add code to create if create is true (sorry,
// too lazy to actually code this up)
foreach(var t in list)
f(t,args);
return list;
}
Eu recomendaria para criar métodos de extensão que internamente usar o LinQ como este:
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Aqui alguns exemplos de uso:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
(Ver https://github.com/cs-util-com/cscore#ienumerable-extensions para mais exemplos)