Friday, 23 April 2010

C# SplitEvery



private static IEnumerable<IEnumerable<T>> SplitEvery<T>(this IEnumerable<T> xs, int n)
{
    return xs.Unfold(ys => ys.Take(n), ys => ys.Any(), ys => ys.Skip(n));
}

private static IEnumerable<T> Unfold<T>(this T x, Func<T, T> h, Func<T, bool> p, Func<T, T> t)
{
    for (var i = x; p(i); i = t(i))
        yield return h(i);
}

2 comments:

Anonymous said...

It's O(N^2), right? (Because of how Skip works.)

holoed said...

Yes, I think it's O(N^2).