Say I need to evaluate a expression as true or false starting from a sample input string like
True or False or ( False or True )
we suppose do not do any validation check.
Bellow we have a working sample that don’t use brackets, and I need to add the brackets support…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine();
// suppose the user introduces a valid input like:
// True or False or ( False or True )
var stringTokens = input.Split(" ".ToCharArray());
List<Token> tokens = new List<Token>();
foreach (string token in stringTokens)
{
tokens.Add(new Token(token));
}
bool result = Token.GetResult(tokens.ToArray());
Console.WriteLine("The result is - {0}!", result);
Console.ReadKey();
}
class Token
{
public readonly Linker Linker;
public readonly bool? Value;
public Token(string text)
{
switch (text.Trim().ToLower())
{
case "true":
Value = true; break;
case "false":
Value = false; break;
case "(":
Linker = Program.Linker.LeftBracket; break;
case ")":
Linker = Program.Linker.RightBracket; break;
case "and":
Linker = Program.Linker.And; break;
case "or":
Linker = Program.Linker.Or; break;
default: break;
}
}
public bool IsLinker
{ get { return !Value.HasValue; } }
public static bool GetResult(params Token[] tokens)
{
bool result = true;
Linker previousLinker = Linker.And;
// this is some bull code...
// please help
foreach (var token in tokens)
{
if (token.IsLinker)
previousLinker = token.Linker;
else
{
if (previousLinker == Linker.And)
result = result && token.Value.Value;
else if (previousLinker == Linker.And)
result = result || token.Value.Value;
else // brackets
{
previousLinker = Linker.And;
//result = result; // NO idea here...
}
}
}
return result;
}
}
public enum Linker
{
None, And, Or,
LeftBracket,
RightBracket
}
}
}
I should mention that I can’t use the Dynamic Link Library, because I already use it… in fact, my question is strongly linked with this one: Using brackets in dynamic .NET expressions
I just want to understand how to group some booleans with brackets… Thanks!
You should make
GetResultfunction recursive.When your foreach loop meets
Linker.LeftBracketit should callGetResult(nonProcessedTokents)without the processed tokens. And when your loop meetsLinker.RightBracketit’d evaluate and return the result. This method’ll help to handle with nested brackets too. Something like that:Or try this library: Flee.