Skip to content

Add cons pattern matching for IEnumerable<T> #36

Description

@DavidArno
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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions