[英]What is the std::partial_sum equivalent in C#?
該操作似乎是結合 map(又名 Select)和 reduce(又名 Aggregate)操作的弱版本,僅限於二元操作。 我們可以做得更好!
public static IEnumerable<R> MyAggregate<T, R>(
this IEnumerable<T> items,
R seed,
Func<T, R, R> mapper)
{
R current = seed;
foreach(T item in items)
{
current = mapper(item, current);
yield return current;
}
}
現在你想要的功能只是一個特例:
static IEnumerable<int> PartialSum(this IEnumerable<int> items) =>
items.MyAggregate(0, (i, s) => s + i);
評論者 Tom Blodget 指出,這要求求和運算具有身份; 如果你沒有呢? 在這種情況下,您必須放棄使 sum 類型與 summand 類型不同的能力:
public static IEnumerable<T> PartialSum<T>(
this IEnumerable<T> items,
Func<T, T, T> sum)
{
bool first = true;
T current = default(T);
foreach(T item in items)
{
current = first ? item : sum(current, item);
first = false;
yield return current;
}
}
你可以使用它
myints.PartialSum((i, s) => i + s);
嘗試這個:
int[] values = new[] { 1, 2, 3, 4 };
var result = values.Select ((x, index) => values.Take (index + 1).Sum ());
結果: 1, 3, 6, 10
但是如果您關心性能,最好編寫自己的方法。
編輯:
public static IEnumerable<T> MyAggregate<T> (this IEnumerable<T> items, Func<T, T, T> mapper)
{
bool processingFirstElement = true;
T accumulator = default (T);
foreach (T item in items)
{
if (processingFirstElement)
{
processingFirstElement = false;
accumulator = item;
}
else
{
accumulator = mapper (accumulator, item);
}
yield return accumulator;
}
}
現在:
int[] values = new int[] { 1, 2, 3, 4 };
var result = values.MyAggregate ((accumulator, item) => accumulator + item).ToList ();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.