/// <summary> /// Applies an accumulator delegate over a sequence starting with a given seed value, yielding each intermediate result. The <paramref name="seed"/> value is the first element of the source sequence. Each element of the source sequence is only evaluated once. /// </summary> /// <typeparam name="TSource">The type of elements in the source sequence.</typeparam> /// <typeparam name="TResult">The type of elements in the resulting sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="seed">The initial seed value.</param> /// <param name="accumulator">The accumulator delegate. The first parameter passed to the accumulator delegate is the previous intermediate result; the second parameter is the current element of the source sequence.</param> /// <returns>The results of the accumulator delegate.</returns> public static IEnumerable <TResult> Scan <TSource, TResult>(this IEnumerable <TSource> source, TResult seed, Func <TResult, TSource, TResult> accumulator) { IEnumerable <TResult> scan = EnumerableSource.Defer(() => { TResult current = seed; return(source.Select(x => current = accumulator(seed, x))); }); return(EnumerableSource.Return(seed).Concat(scan)); }
/// <summary> /// Applies an accumulator delegate over a sequence, yielding each intermediate result. The first element of the returned sequence is the first element of the source sequence. Each element of the source sequence is only evaluated once. /// </summary> /// <typeparam name="T">The type of elements in the sequence.</typeparam> /// <param name="source">The source sequence.</param> /// <param name="accumulator">The accumulator delegate. The first parameter passed to the accumulator delegate is the previous intermediate result; the second parameter is the current element of the source sequence.</param> /// <returns>The results of the accumulator delegate.</returns> public static IEnumerable <T> Scan <T>(this IEnumerable <T> source, Func <T, T, T> accumulator) { return(EnumerableSource.Defer(() => { T current = default(T); bool currentValid = false; return source.Select(x => { if (currentValid) { current = accumulator(current, x); } else { currentValid = true; current = x; } return current; }); })); }