代码拉取完成,页面将自动刷新
using static PatternMatchingExpr.Operator;
namespace PatternMatchingExpr;
public abstract partial class Expr<T> where T : IBinaryNumber<T>
{
public class BinaryExpr : Expr<T>
{
public BinaryExpr(BinaryOperator op, Expr<T> left, Expr<T> right) => (Op, Left, Right) = (op, left, right);
public BinaryOperator Op { get; }
public Expr<T> Left { get; }
public Expr<T> Right { get; }
public void Deconstruct(out BinaryOperator op, out Expr<T> left, out Expr<T> right) => (op, left, right) = (Op, Left, Right);
public override T Eval(params (string Name, T Value)[] args) => Op switch
{
BinaryOperator(var op) => op switch
{
Operators.Add => Left.Eval(args) + Right.Eval(args),
Operators.Sub => Left.Eval(args) - Right.Eval(args),
Operators.Mul => Left.Eval(args) * Right.Eval(args),
Operators.Div => Left.Eval(args) / Right.Eval(args),
Operators.And => Left.Eval(args) & Right.Eval(args),
Operators.Or => Left.Eval(args) | Right.Eval(args),
Operators.Xor => Left.Eval(args) ^ Right.Eval(args),
Operators.Eq => Left.Eval(args) == Right.Eval(args) ? T.One : T.Zero,
Operators.Ne => Left.Eval(args) != Right.Eval(args) ? T.One : T.Zero,
Operators.Gt => Left.Eval(args) > Right.Eval(args) ? T.One : T.Zero,
Operators.Lt => Left.Eval(args) < Right.Eval(args) ? T.One : T.Zero,
Operators.Ge => Left.Eval(args) >= Right.Eval(args) ? T.One : T.Zero,
Operators.Le => Left.Eval(args) <= Right.Eval(args) ? T.One : T.Zero,
Operators.LogicalAnd => Left.Eval(args) == T.Zero || Right.Eval(args) == T.Zero ? T.Zero : T.One,
Operators.LogicalOr => Left.Eval(args) == T.Zero && Right.Eval(args) == T.Zero ? T.Zero : T.One,
< Operators.Add or > Operators.LogicalOr => throw new InvalidOperationException($"Unexpected a binary operator, but got {op}.")
},
_ => throw new InvalidOperationException("Unexpected a binary operator.")
};
public override string ToString() => $"({Left}) {Op.Operator.GetName()} ({Right})";
public override bool Equals(object? obj) => obj is BinaryExpr({ Operator: var op }, var left, var right) && (op, left, right).Equals((Op.Operator, Left, Right));
public override int GetHashCode() => (Op, Left, Right).GetHashCode();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。