Skip to content

Instantly share code, notes, and snippets.

@arialdomartini
Created May 11, 2018 05:36
Show Gist options
  • Save arialdomartini/9024368dd07c5ab73005f839675fd635 to your computer and use it in GitHub Desktop.
Save arialdomartini/9024368dd07c5ab73005f839675fd635 to your computer and use it in GitHub Desktop.
Sum of tuples, pure functional
public class MyTupleIntTest
{
[Fact]
public void should_retain_values()
{
var tuple = MyTuple.Build(44, 100);
tuple.First().Should().Be(44);
tuple.Second().Should().Be(100);
}
[Fact]
public void should_add_tuples()
{
var tuple1 = MyTuple.Build(2, 5);
var tuple2 = MyTuple.Build(100, 50);
var result = tuple1.Add(tuple2);
result.First().Should().Be(102);
result.Second().Should().Be(55);
}
}
public static class MyTuple
{
public static Func<Func<int, int, int>, int> Build(int a, int b) => f => f(a, b);
public static int First(this Func<Func<int, int, int>, int> tuple) => tuple((a, _) => a);
public static int Second(this Func<Func<int, int, int>, int> tuple) => tuple((_, b) => b);
public static Func<Func<int, int, int>, int> Add(
this Func<Func<int, int, int>, int> a,
Func<Func<int, int, int>, int> b) => Build(a.First() + b.First(), a.Second() + b.Second());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment