Permalink
Browse files

Four4Sample - support breaking out of search early

  • Loading branch information...
bobbymcr committed Mar 11, 2018
1 parent dc5743c commit ee225ff120fed5619357768286e7b149b0703195
@@ -11,6 +11,19 @@ namespace Four4.Test
public sealed class ExpressionSearchTest
{
[Fact]
public void CancelSearch()
{
ExpressionSearch search = new ExpressionSearch();
search.AddOperand("4");
search.AddBinary("+");
int count = 0;
search.Run(e => ++count < 3);
count.Should().Be(3);
}
[Fact]
public void OneOperandAndOneBinaryOperator()
{
@@ -1476,8 +1489,13 @@ public void TwoOperandsAndTwoBinaryOperators()
private static void TestSearch(ExpressionSearch search, string expected)
{
List<string> expressions = new List<string>();
Func<Expression, bool> found = e =>
{
expressions.Add(e.ToString());
return true;
};
search.Run(e => expressions.Add(e.ToString()));
search.Run(found);
expressions.Sort();
string.Join(Environment.NewLine, expressions).Should().Be(expected);
@@ -35,40 +35,54 @@ public void AddUnary(string op)
this.unaryOps.Add(op);
}
public void Run(Action<Expression> each)
public void Run(Func<Expression, bool> each)
{
this.Run(default(Expression), each);
}
private void Run(Expression expr, Action<Expression> each)
private bool Run(Expression expr, Func<Expression, bool> each)
{
if (!expr.IsValid)
{
return;
return true;
}
if (expr.Result.IsValid)
{
each(expr);
if (!each(expr))
{
return false;
}
}
if (expr.NumeralCount < 4)
{
foreach (string op in this.ops)
{
this.Run(expr.Append(op), each);
if (!this.Run(expr.Append(op), each))
{
return false;
}
}
}
foreach (string bop in this.binaryOps)
{
this.Run(expr.Append(bop), each);
if (!this.Run(expr.Append(bop), each))
{
return false;
}
}
foreach (string uop in this.unaryOps)
{
this.Run(expr.Append(uop), each);
if (!this.Run(expr.Append(uop), each))
{
return false;
}
}
return true;
}
}
}

0 comments on commit ee225ff

Please sign in to comment.