Skip to content

Fold variation that captures remainder elements #337

@atifaziz

Description

@atifaziz

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 } }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions