Skip to content

Instantly share code, notes, and snippets.

@ToJans
Last active December 10, 2015 10:08
Show Gist options
  • Save ToJans/4418591 to your computer and use it in GitHub Desktop.
Save ToJans/4418591 to your computer and use it in GitHub Desktop.
Pattern matching in c#
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Toopsie.Parsers;
namespace Toopsie.Specs
{
[TestClass]
public class PatternMatchFizzbuzz
{
PMatch fizzbuzz;
static IEnumerable<int> Range(int from, int to)
{
for (var i = from; i <= to; i++)
yield return i;
}
[TestInitialize]
public void Setup()
{
fizzbuzz = new PMatch();
fizzbuzz
.When<int>(x => x % 15 == 0).Do(x => "fizzbuzz")
.When<int>(x => x % 3 == 0).Do(x => "fizz")
.When<int>(x => x % 5 == 0).Do(x => "buzz")
.When<int>().Do(x => x)
.When<IEnumerable<int>>().Do(x => from val in x select fizzbuzz.Invoke(x))
.When<int, int>((from, to) => to >= from).Do((from, to) => fizzbuzz.Invoke(Range(from, to)))
.When("fizzbuzz").Do(x => "Aha, you found the easter egg!");
}
[TestMethod]
public void CurryFizzbuzz()
{
fizzbuzz.Invoke(3).ShouldBe("fizz");
fizzbuzz.Invoke(4).ShouldBe(4);
fizzbuzz.Invoke(45).ShouldBe("fizzbuzz");
fizzbuzz.Invoke(1, 5).ToArray().ShouldBe(new object[] { "fizzbuzz", 2, "fizz", 4, "buzz" });
fizzbuzz.Invoke("fizzbuzz").ShouldBe("Aha, you found the easter egg!");
}
}
}
@ToJans
Copy link
Author

ToJans commented Dec 31, 2012

It compiles, but the test fails ATM

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