Last active
October 26, 2019 17:31
-
-
Save waf/fdc243bd6bdcb1c6ab5134088223b3b0 to your computer and use it in GitHub Desktop.
C# 8 port of F# brace matching
This file contains 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
// | |
// C# 8 port of F# brace matching. | |
// | |
using System; | |
using System.Linq; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace BraceMatching | |
{ | |
using ParseState = Nullable<int>; // we get to cheat a bit because the C# compiler will "map" over nullable types implicitly | |
using ParseResult = Boolean; | |
[TestClass] | |
public class CurlyBraces | |
{ | |
public ParseResult AreCurlyBracesMatched(string input) | |
{ | |
static ParseState OpenBrace(ParseState state) => | |
state + 1; | |
static ParseState ClosingBrace(ParseState state) => | |
state - 1 as int? switch | |
{ | |
int n when n >= 0 => n, | |
_ => null, | |
}; | |
return input | |
.Aggregate( | |
0 as int?, | |
(result, character) => character switch | |
{ | |
'{' => OpenBrace(result), | |
'}' => ClosingBrace(result), | |
_ => throw new ArgumentException("Invalid character") | |
} | |
) switch | |
{ | |
0 => true, | |
_ => false | |
}; | |
} | |
[DataTestMethod] | |
[DataRow("{}", true)] | |
[DataRow("{{}}", true)] | |
[DataRow("{{{{}", false)] | |
[DataRow("{}}}}", false)] | |
[DataRow("{", false)] | |
[DataRow("}", false)] | |
// [DataRow("}{", true)] fails in original algorithm? | |
public void Test_AreCurlyBracesMatched(string input, bool expected) | |
{ | |
bool result = AreCurlyBracesMatched(input); | |
Assert.AreEqual(expected, result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment