Revisiting Elevate: Seq.pairwise for C#

I’ve been working on a few different projects over the last few months including some work outside of the .NET space. This has been good for my clients, but not so good for Elevate. Fortunately, I found some time the other day to add a new feature: a pairwise implementation for C#.

In F#, the Seq.pairwise function enables you to walk a sequence two elements at a time. In F# Interactive, it looks like this:

> [0..3]
  |> Seq.pairwise;;
val it : seq<int * int> = seq [(0, 1); (1, 2); (2, 3)]

It’s an especially useful function to have in your arsenal if you need to compute deltas in a sequence:

> [0;2;5;6;2;5]
  |> Seq.pairwise
  |> (fun (l, r) -> r - l)
  |> Seq.toList;;
val it : int list = [2; 3; 1; -4; 3]

I chose to implement pairwise a little differently in C#. Because C# doesn’t have language support for pattern matching against tuples, I find that they are more clumsy to use than in F#. So, instead of having pairwise return an IEnumerable of Tuples, I created two overloads of pairwise.

One overload accepts a Func to map elements from an IEnumerable:

public void PairwiseSelect()
    //given a sequence
    var values = 0.Through(5);

    //we can walk the list two elements at a time by using pairwise
    //and find the sum of the two elements
    var result = 
        .Pairwise((x, y) => x+y);

    Assert.That(result, Is.EqualTo(new[] { 1, 3, 5, 7, 9 }));

While the other accepts an action to perform while walking an IEnumerable two elements at a time:

//given a sequence
var values = 0.Through(5);

//we can also use pairwise to execute an action while
//walking a sequence two elements at a time
values.Pairwise((x, y) => Console.WriteLine(x*y));

I don’t use pairwise as frequently as some functions in Elevate/LINQ/Seq, but it’s very useful when you need it. Hopefully I’ll find more time in the upcoming weeks to contribute more regularly to Elevate!

This entry was posted in C#, Elevate, F#. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>