Last active
December 10, 2015 10:08
-
-
Save ToJans/4418591 to your computer and use it in GitHub Desktop.
Pattern matching in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It compiles, but the test fails ATM