-
Notifications
You must be signed in to change notification settings - Fork 419
Open
Labels
Description
The current implementation of Fold throws when the source sequence doesn't contain exactly the same number of elements as the arity of the folder function. Consider adding a variation that captures remainder or tail elements.
Prototype
Below is an example shown for folder function with an arity of 3:
public static TResult FoldVar<T, TResult>(this IEnumerable<T> source,
Func<T, T, T, IEnumerable<T>, TResult> folder)
{
InvalidOperationException Error() =>
throw new InvalidOperationException("Insufficient elements.");
using (var e = source.GetEnumerator())
{
if (!e.MoveNext()) throw Error(); var first = e.Current;
if (!e.MoveNext()) throw Error(); var second = e.Current;
if (!e.MoveNext()) throw Error(); var third = e.Current;
var rest = new List<T>();
while (e.MoveNext())
rest.Add(e.Current);
return folder(first, second, third, rest);
}
}Note that this version still throws an error if there are insufficient elements in the source sequence but not otherwise.
Usage
var result =
Enumerable.Range(1, 10)
.FoldVar((x, y, z, rest) => new
{
First = x,
Second = y,
Third = z,
Tail = rest,
});
// result = { First = 1, Second = 2, Third = 3, Tail = { 4, 5, 6, 7, 8, 9, 10 } }