Friday, April 26, 2013

Sasa.Linq.Enumerables - Extensions on IEnumerable<T>

This is the seventeenth post in my ongoing series covering the abstractions in Sasa. Previous posts:

In my opinion, the release of .NET 3.5 and LINQ to Objects was one of the greatest productivity and safety enhancements to .NET since its inception. It enabled the concise expression of highly generic algorithms depending solely on the simple notion of an iterable stream, IEnumerable<T>. You could then specify semantics for duplicates, ordering, and grouping constraints over streams with a nice query syntax or a simple first-class function syntax.

The advent of extension methods allowed such extensions to be packaged into a neat, consistent framework under System.Linq.Enumerable. Sasa.Linq.Enumerables extends the functionality for IEnumerable<T> even further.

Sasa.Linq.Enumerables.Append

Sasa.Linq.Enumerables.Append is an extension method on IEnumerable<T> to add a single element to the end of a sequence:

IEnumerable<int> source = new[] { 2, 99, 8 };
IEnumerable<int> sourcePlusOne = source.Append(-10);
foreach (var x in sourcePlusOne)
{
    Console.WriteLine(x);
}
// output:
// 2
// 99
// 8
// -10

Sasa.Linq.Enumerables.Apply

Sasa.Linq.Enumerables.Apply is an extension on IEnumerable<T> that applies an Action<T> to every value as the stream is being iterated:

IEnumerable<int> source = new[] { 2, 99, 8 }
                          .Apply(Console.Write);
foreach (var x in source)
{
    Console.WriteLine();
}
// output:
// 2
// 99
// 8

Sasa.Linq.Enumerables.CompareTo

Sasa.Linq.Enumerables.CompareTo is an extension on IEnumerable<T> that performs an element-wise comparison between two streams in the same vein as the IComparable<T> interface:

IEnumerable<int> largest = new[] { 3, 99, 8 };
IEnumerable<int> larger  = new[] { 2, 99, 8 };
IEnumerable<int> smaller = new[] { 2, 98, 8 };

Console.WriteLine(largest.CompareTo(larger));
Console.WriteLine(larger.CompareTo(smaller));
Console.WriteLine(smaller.CompareTo(largest));
Console.WriteLine(smaller.CompareTo(smaller));
// output:
// 1
// 1
// -1
// 0

Sasa.Linq.Enumerables.Consume

Sasa.Linq.Enumerables.Consume is an extension on IEnumerable<T> that consumes a whole stream in one go:

static IEnumerable<int> Foo()
{
    for (int i = 0; i < 3; ++i)
    {
        Console.WriteLine(i);
        yield return i;
    }
}
...
Foo().Consume(); // consume stream and return when done

// output:
// 0
// 1
// 2

Sasa.Linq.Enumerables.CopyTo

Sasa.Linq.Enumerables.CopyTo is an extension on IEnumerable<T> that copies elements from the stream into a pre-allocated array:

IEnumerable<int> source = new[] { 3, 99, 8, -5, 12, -999 };
int[] buffer = new int[3];
source.CopyTo(buffer, 0);
foreach (var x in buffer)
{
    Console.Write("{0}, ", x);
}
// output:
// 3, 99, 8,

Sasa.Linq.Enumerables.Difference

Sasa.Linq.Enumerables.Difference is an extension on IEnumerable<T> that produces a stream of Change<T> values indicating the changes needed to transform one stream into another:

IEnumerable<int> first = new[] { 3, 99, 8, -5, 12, -9 };
IEnumerable<int> second = new[] { 3, 99, -5, 12, 66, 234, -9 };
IEnumerable<Change<int>> diff = first.Difference(second);
foreach (var x in diff)
{
    Console.WriteLine(x);
}
// output:
// -1:99
// +1:99,8
// +5:66, 234

Basically, the 'diff' stream in the above sample describes the changes you have to make to 'first' in order to transform it into the stream 'second'. This is fully described by the output which specifies a subtraction at position 1 of the value 99, an addition at position 1 of values 99 and 8, and the addition of two values at position 5 of 66 and 234.

Sasa.Linq.Enumerables.Do

Sasa.Linq.Enumerables.Do is an extension on IEnumerable<T> that fully consumes a stream while applying a function to each element:

IEnumerable<int> source = new[] { 2, 99, 8 };
source.Do(Console.WriteLine);
// output:
// 2
// 99
// 8

Sasa.Linq.Enumerables.Flatten

Sasa.Linq.Enumerables.Flatten is an extension on IEnumerable<T> that flattens a nested sequence:

IEnumerable<IEnumerable<int>> source = new int[][]
{
    new[] { 2, 99 },
    new[] { 8 }
};
IEnumerable<int> flat = source.Flatten();
flat.Do(Console.WriteLine);
// output:
// 2
// 99
// 8

This is functionally equivalent to:

IEnumerable<int> flat = source.SelectMany(x => x);

Except the C# compiler won't have to create so many delegates in all the various assemblies that flatten sequences.

Sasa.Linq.Enumerables.Format

Sasa.Linq.Enumerables.Format is a set of extension method overloads on IEnumerable<T> that make it easy to construct a string from a sequence. Basically, you provide a sequence and a value separator, like ",", and Format will output each value in the sequence spaced with the separator:

IEnumerable<int> source = new[] { 2, 99, 8 };
string formatted = source.Format(", ");
Console.WriteLine(formatted);
// output:
// 2, 99, 8

Sasa.Linq.Enumerables.Generate

Sasa.Linq.Enumerables.Generate is a static method used to construct sequences of values by taking a seed value and a generator function:

Func<int, Option<int>> step = x => x < 3 ? x + 1:
                                           Option<T>.None;
IEnumerable<int> source = Enumerables.Generate(0, step);
Console.WriteLine(source.Format(", "));
// output:
// 0, 1, 2, 3

The generator function returns an Option<T>, so terminating the generator requires simply returning Option<T>.None.

Sasa.Linq.Enumerables.Push

Sasa.Linq.Enumerables.Push is an extension on IEnumerable<T> that pushes an element to the front of an enumerable sequence:

IEnumerable<int> source = new[] { 2, 99, 8 };
Console.WriteLine(source.Push(-1).Format(","));
// output:
// -1, 2, 99, 8

Sasa.Linq.Enumerables.ReplaceElementAt

Sasa.Linq.Enumerables.ReplaceElementAt is an extension on IEnumerable<T> that replaces the element at a specified index with a new value:

IEnumerable<int> source = new[] { 2, 99, 8 }
                         .ReplaceElementAt(index: 1, value: -1);
Console.WriteLine(source.Format(","));
// output:
// 2, -1, 8

Sasa.Linq.Enumerables.Transpose

Sasa.Linq.Enumerables.Transpose is an extension on a nested sequence, IEnumerable<IEnumerable<T>> that transposes the rows and columns:

IEnumerable<IEnumerable<int>> source = new int[][]
{
    new[] { 2, 99 },
    new[] { 8, -10 }
};
// transpose the rows and columns
foreach (var row in source.Transpose())
{
    foreach (var column in row)
    {
        Console.Write("{0}, ", column);
    }
    Console.WriteLine();
}
flat.Do(Console.WriteLine);
// output:
// 2, 8
// 99, -10

Note that this method will handle jagged sequences, but transposing twice will not necessarily recover the same sequence as the original input. All the jagged entries will be pushed to the last row.

Sasa.Linq.Enumerables.Zip

Sasa.Linq.Enumerables.Zip is a set of extension method overloads on IEnumerable<T> that combines streams together element-wise, returning a stream of Sasa's tuples. This is known as "zipping" streams, analogously to the operation of a physical zipper where the teeth pair up one after another:

IEnumerable<int> source1 = new[] { 2, 99 };
IEnumerable<int> source2 = new[] { 8, -10 };
IEnumerable<Pair<int, int>> zipped = source1.Zip(source2);

Console.WriteLine(zipped.Format("\r\n"));
// output:
// (2, 8)
// (99, -10)

There is a zip overload for each of Sasa's tuple types, so you can zip up to 4 streams together.

Sasa.Linq.Enumerables.ZipWith

Sasa.Linq.Enumerables.ZipWith is a set of extension method overloads on IEnumerable<T> that combines the elements of streams together element-wise using a client-specified function, returning a stream of values. This is known as "zipping" streams, analogously to the operation of a physical zipper where the teeth pair up one after another:

IEnumerable<int> source1 = new[] { 2, 99 };
IEnumerable<int> source2 = new[] { 8, -10 };
IEnumerable<Pair<int, int>> zipped =
    source1.ZipWith(source2, (x,y) => Tuples.Create(x,y));

Console.WriteLine(zipped.Format("\r\n"));
// output:
// (2, 8)
// (99, -10)

Like the Enumerables.Zip extension, ZipWith is defined for zipping up to 4 streams.

No comments: