SuccincT icon indicating copy to clipboard operation
SuccincT copied to clipboard

Add cons pattern matching for IEnumerable<T>

Open DavidArno opened this issue 8 years ago • 3 comments

var result = someEmptyList.Match().To<int>()
                          .Empty().Do(0)
                          .Result();
// result == 0

var list = new List<int>{1};
var result = list.Match().To<int>()
                 .Empty().Do(0)
                 .Single().Do(x => x)
                 .Result();
// result == 1

var list2 = new List<int>{0};
var result = list2.Match().To<int>()
                  .Empty().Do(0)
                  .Single().Where(x => x > 1).Do(1)
                  .Single().Do(2)
                  .Result();
// result == 2

var list3 = new List<int>{1, 2};
var result = list3.Match().To<int>()
                  .Empty().Do(0)
                  .Single().Do(x => x)
                  .Cons().Do((_, t) => t)
                  .Result();
// result == 2

Requiring Cons().Do() to recursively process the collection would be very inefficient. So RecurseTail method will be available to allow the collection to be iterated over:

var list4 = new List<int>{1, 2, 3, 4};
var result = list4.Match().To<int>()
                  .Single().Do(x => x)
                  .Cons().RecurseTail().Do((head, result) => head + result)
                  .Result();
// result == 1 + 2 + 3 + 4 == 10

My initial thoughts on how to best handle this, if RecurseTail is used, then we iterate over the elements, storing them in eg a stack and then pop them off one at a time, applying the Single match to the last item, and Cons matches to everything else to arrive at a final result.

Not sure yet if an Action version is even needed.

DavidArno avatar May 30 '17 16:05 DavidArno

Added to v3.1. Still needs documenting though.

DavidArno avatar Feb 13 '18 08:02 DavidArno

Moved to the v4 milestone as the documentation for this will be released with that release.

DavidArno avatar Oct 10 '19 07:10 DavidArno

v4 is released, but it still needs documenting.

DavidArno avatar Feb 17 '20 10:02 DavidArno