Skip to content

Instantly share code, notes, and snippets.

@waf
Last active October 26, 2019 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waf/fdc243bd6bdcb1c6ab5134088223b3b0 to your computer and use it in GitHub Desktop.
Save waf/fdc243bd6bdcb1c6ab5134088223b3b0 to your computer and use it in GitHub Desktop.
C# 8 port of F# brace matching
//
// 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