33 lines
1.2 KiB
C#
33 lines
1.2 KiB
C#
namespace Bts.BooleanExpressions;
|
|
|
|
using Bts.BooleanExpressions.Arguments;
|
|
|
|
class BoundBooleanExpression : IBooleanExpression {
|
|
readonly IBooleanExpression expression;
|
|
readonly IDictionary<string, FunctionDefinition> definitions;
|
|
readonly Dictionary<string, object?> identifiers;
|
|
|
|
public BoundBooleanExpression(
|
|
IBooleanExpression expression, IEnumerable<Definition>? definitions = null) {
|
|
this.expression = expression;
|
|
var defs = definitions ?? Enumerable.Empty<Definition>();
|
|
identifiers = defs.ToDictionary(
|
|
kv => kv.id, kv => (object?)kv.exp);
|
|
this.definitions = extractFunctions(defs).ToDictionary(kv => kv.Key, kv => kv.Value);
|
|
}
|
|
|
|
public bool Evaluate(IDictionary<string, object?> env) {
|
|
foreach (var kv in env) {
|
|
identifiers[kv.Key] = kv.Value;
|
|
}
|
|
env = new EvaluationEnvironment(identifiers, definitions);
|
|
return expression.Evaluate(env);
|
|
}
|
|
|
|
static IEnumerable<KeyValuePair<string, FunctionDefinition>> extractFunctions(
|
|
IEnumerable<Definition> definitions) =>
|
|
definitions.Select(d =>
|
|
new KeyValuePair<string, FunctionDefinition>(
|
|
Function.FunctionPrefix + d.id, new(d.id, d.args.ToList(), d.exp)));
|
|
}
|