/// <summary> /// Iterpreter client context /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button5_Click(object sender, EventArgs e) { Context ctx = new Context(textBox1.Text.ToString().ToLower()); string context = textBox1.Text.ToString().ToLower(); AbstractExpression background = new TerminalExpression("background"); AbstractExpression operation = new TerminalExpression("color"); if (ctx.Input.Length == 0) { textBox1.ForeColor = Color.Red; textBox1.Text = "Bad Command!"; textBox1.ForeColor = Color.Black; } else { AbstractExpression command = new BackGroundColorExpression(background, operation, _Form1); if (command.Interpreter(ctx.Input)) { textBox1.Text = string.Empty; } else { textBox1.Text = "Bad Command!"; } } caretaker.Backup(); originator.SetState(_Form1.BackColor.Name); }
public void CheckExpressions() { // Arrange Expression opr1 = new TerminalExpression(3.5); Expression opr2 = new TerminalExpression(2); Expression add = new Addition(opr1, opr2); Expression subs = new Substraction(opr1, opr2); Expression mult = new Multiplication(opr1, opr2); Expression div = new Division(opr1, opr2); Expression pow = new Power(opr1, opr2); Expression sqrt = new SquareRoot(opr1); Expression mod = new Modulus(opr1, opr2); // Act double addRes = add.solve(); double subsRes = subs.solve(); double multRes = mult.solve(); double divRes = div.solve(); double powRes = pow.solve(); double sqrtRes = sqrt.solve(); double modRes = mod.solve(); // Assert Assert.AreEqual(3.5 + 2, addRes); Assert.AreEqual(3.5 - 2, subsRes); Assert.AreEqual(3.5 * 2, multRes); Assert.AreEqual(3.5 / 2, divRes); Assert.AreEqual(Math.Pow(3.5, 2), powRes); Assert.AreEqual(Math.Pow(3.5, 0.5), sqrtRes); Assert.AreEqual(3.5 % 2, modRes); }
public IExpression GetMaleExpression() { IExpression robert = new TerminalExpression("Robert"); IExpression john = new TerminalExpression("John"); return(new OrExpression(robert, john)); }
public IExpression GetMarriedWomanExpression() { IExpression julie = new TerminalExpression("Julie"); IExpression married = new TerminalExpression("Married"); return(new AndExpression(julie, married)); }
void PopPopApplyPush() { Expression Expr2 = this.Value_Stack.Peek(); this.Value_Stack.Pop(); if (isUnaryExpression(Expr2)) { TerminalExpression Term_Expr2 = new TerminalExpression(Expr2.Solve()); Expr2 = Term_Expr2; } Expression Expr1 = this.Value_Stack.Peek(); this.Value_Stack.Pop(); if (isUnaryExpression(Expr1)) { TerminalExpression Term_Expr1 = new TerminalExpression(Expr1.Solve()); Expr1 = Term_Expr1; } Expression op = this.Operator_Stack.Peek(); this.Operator_Stack.Pop(); if (((Operator)op).GetOp() == '/' && Expr2.Solve() == 0) { throw new DivisionByZeroException(); } else { this.Value_Stack.Push(applyOp(Expr1, op, Expr2)); } }
private double CalculateBinary(TerminalExpression a, TerminalExpression b) { // double hasil = 0; if (op == '+') { AddExpression hasil = new AddExpression(a, b); //hasil = a + b; return(hasil.solve()); } else if (op == '-') { SubstractExpression hasil = new SubstractExpression(a, b); //hasil = a - b; return(hasil.solve()); } else if (op == '*') { MultiplyExpression hasil = new MultiplyExpression(a, b); //hasil = a * b; return(hasil.solve()); } else if (op == '÷') { DivisionExpression hasil = new DivisionExpression(a, b); //hasil = a / b; return(hasil.solve()); } return(0); }
/// <summary> /// TerminalExpression を作成する. /// </summary> /// <param name="name"></param> /// <returns></returns> public static GeneratedExpression CreateTerminal(string name) { TerminalExpression exp = new TerminalExpression(); exp.Type = ExpressionType.Terminal; exp.Name = name; return(exp); }
public void NegativeRootExceptions() { // Assign Expression neg = new TerminalExpression(-25); Expression negRoot = new SquareRoot(neg); // Act double negRootRes = negRoot.solve(); }
public void ZeroDivExceptions() { // Assign Expression neg = new TerminalExpression(-25); Expression zero = new TerminalExpression(0); Expression zeroDiv = new Division(neg, zero); // Act double zeroDivRes = zeroDiv.solve(); }
/// <summary> /// Creates a new instance of the <see cref="EventHandler"/> class. /// </summary> /// <param name="name">The name of the event being handled.</param> /// <param name="parameter">The parameter for the event handler, if necessary.</param> /// <param name="unsafe">Whether the event handler is unsafe.</param> /// <param name="atomic">Whether the event handler is atomic.</param> /// <param name="fileName">The name of the file.</param> /// <param name="errorToken">The token to report any compiler errors to.</param> public EventHandler(string name, TerminalExpression parameter, bool @unsafe, bool atomic, string fileName, IToken errorToken) { Name = name; Parameter = parameter; Unsafe = @unsafe; Atomic = atomic; FileName = fileName; ErrorToken = errorToken; }
/// <summary> /// Sets up a test expression rule of "big" and "scary" and "pink". /// </summary> public InterpreterTest() { var term1 = new TerminalExpression("big"); var term2 = new TerminalExpression("scary"); var term3 = new TerminalExpression("pink"); // Non-Terminal expression of "big" AND "scary" var nonTerm1 = new NonterminalExpression(term1, term2); // Non-Terminal expression of ("big" AND "scary") AND "pink" _testExpression = new NonterminalExpression(nonTerm1, term3); }
private void button3_Click(object sender, EventArgs e) { AbstractExpression background = new TerminalExpression("background"); AbstractExpression operation = new TerminalExpression("color"); AbstractExpression command = new BackGroundColorExpression(background, operation, _Form1); caretaker.Undo(); string context = "background color " + originator.State; command.Interpreter(context); commandLogger.logMessage(AbstractLogger.COMMAND, "\nBackground color restored to: " + originator.State); //richTextBox1.AppendText("\nBackground color restored to: "+originator.State ); }
public void Interpereter_Test() { var context = new Context("hello"); var terminalA = new TerminalExpression(); var terminalB = new TerminalExpression(); var nonTerminal = new NonTerminalExpression(); nonTerminal.SubExpressionA = terminalA; nonTerminal.SubExpressionB = terminalB; var result = nonTerminal.Interpret(context); Assert.IsTrue(result.Contains(context.Name)); }
private IExpression GetExpression <T>(string expressionOne, string expressionTwo) { IExpression expression = null; var eOne = new TerminalExpression(expressionOne); var eTwo = new TerminalExpression(expressionTwo); if (typeof(T) == typeof(AndExpression)) { expression = new AndExpression(eOne, eTwo); } else if (typeof(T) == typeof(OrExpression)) { expression = new OrExpression(eOne, eTwo); } return(expression); }
public static void Interpreter() { IExpression person1 = new TerminalExpression("Kushagra"); IExpression person2 = new TerminalExpression("Lokesh"); IExpression isSingle = new OrExpression(person1, person2); IExpression vikram = new TerminalExpression("Vikram"); IExpression committed = new TerminalExpression("Committed"); IExpression isCommitted = new AndExpression(vikram, committed); Console.WriteLine(isSingle.interpreter("Kushagra")); Console.WriteLine(isSingle.interpreter("Lokesh")); Console.WriteLine(isSingle.interpreter("Achint")); Console.WriteLine(isCommitted.interpreter("Committed, Vikram")); Console.WriteLine(isCommitted.interpreter("Single, Vikram")); }
/// <summary> /// Gets the translated code for the grammar structure. /// </summary> /// <returns>The translated code for the grammar structure.</returns> public IEnumerable <Block> Translate(TranslationContext context) { // Create new translation context TranslationContext newContext = new TranslationContext(new Scope(context.CurrentScope), context); List <Block> loopContents = new List <Block>(); foreach (IStatement statement in Statements) { loopContents.AddRange(statement.Translate(newContext)); } if (!Inline) { return(new BlockBuilder(BlockSpecs.Repeat, context).AddParam(Iterations).AddParam(loopContents.ToArray()).Create()); } TerminalExpression tIterations = Iterations as TerminalExpression; if (tIterations == null || tIterations.Type != DataType.Number) { context.ErrorList.Add(new CompilerError("Loop cannot be inlined", ErrorType.InvalidArgument, ErrorToken, FileName)); return(Enumerable.Empty <Block>()); } // Inline loop int repetitions = (int)Math.Floor((double)tIterations.Value); List <Block> inlinedLoopContents = new List <Block>(); for (int i = 0; i < repetitions; i++) { inlinedLoopContents.AddRange(loopContents); } return(inlinedLoopContents); }
static void Main14() { Console.WriteLine("Hello Interpreter Pattern!"); var context = new Context(); var a = new TerminalExpression("a"); var b = new TerminalExpression("b"); var c = new TerminalExpression("c"); context.Add(a, 10); context.Add(b, 15); context.Add(c, 5); int result = new MinusOperation(new PlusOperation(a, b), c).Interpreter(context); Console.WriteLine($"a = {a.Interpreter(context)}"); Console.WriteLine($"b = {b.Interpreter(context)}"); Console.WriteLine($"c = {c.Interpreter(context)}"); Console.WriteLine($"a + b - c = {result}"); Console.ReadLine(); }
// Menghitung hasil operasi <operand1> <operator> <operand2> public double calculate() { Expression temp = new TerminalExpression(0); switch (operatorSign) { case "+": temp = new Addition(operand1, operand2); break; case "-": temp = new Substraction(operand1, operand2); break; case "*": temp = new Multiplication(operand1, operand2); break; case "/": temp = new Division(operand1, operand2); break; case "^": temp = new Power(operand1, operand2); break; case "sqrt": temp = new SquareRoot(operand1); break; case "mod": temp = new Modulus(operand1, operand2); break; } return(temp.solve()); }
/// <summary> /// Creates a new instance of the <see cref="ForLoop"/> class. /// </summary> /// <param name="variable">The name of the counter variable.</param> /// <param name="varType">The data type of the counter variable.</param> /// <param name="start">The expression for the counter start value.</param> /// <param name="end">The expression for the counter end value.</param> /// <param name="step">The expression for the counter stop value. Default is +1.</param> /// <param name="fileName">The name of the file.</param> /// <param name="errorToken">The token to report any compiler errors to.</param> public ForLoop(string variable, DataType varType, IExpression start, IExpression end, TerminalExpression step, string fileName, IToken errorToken) { Variable = variable; VarType = varType; Start = start; End = end; FileName = fileName; ErrorToken = errorToken; Step = step ?? new TerminalExpression(1, DataType.Number); }
static void Main(string[] args) { // Abstract factory IFactory concreteFactory = new WindowsFactory(); var obj1 = concreteFactory.CreateCloneable(); var obj2 = concreteFactory.CreateComparable(); // Builder IBuilder builder = new Builder1(); var director = new Director(builder); var product = director.Construct <IProduct>(); // Factory method Application app = new DrawingApplication(); Document document = app.CreateDocument(); // Prototype Prototype prototype = new ConcretePrototype1(); Prototype newObject = prototype.Clone(); // Command Receiver receiver = new Receiver(); Command command = new ConcreteCommand(receiver); Invoker invoker = new Invoker(); invoker.SetCommand(command); invoker.ExecuteCommand(); // Interpreter var context = new Context(); AbstrcatExpression experssion1 = new NonterminalExpression(); AbstrcatExpression expression2 = new TerminalExpression(); experssion1.Interpret(context); expression2.Interpret(context); // Mediator ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("How are you?"); c2.Send("Fine, thanks"); // Memoto Originator o = new Originator(); o.State = "On"; // Store internal state Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); // Continue changing originator o.State = "Off"; // Restore saved state o.SetMemento(c.Memento); // Observer ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s, "X")); s.Attach(new ConcreteObserver(s, "Y")); s.Attach(new ConcreteObserver(s, "Z")); // Change subject and notify observers s.SubjectState = "ABC"; s.Notify(); }
private double solvePostfixQueue() { /** DESKRIPSI **/ /* Menyelesaikan ekspresi Postfix di queue menjadi nilai */ /** KAMUS DATA **/ Stack <TerminalExpression> operationStack; // Stack untuk menyimpan nilai-nilai operasi Elemen <string> queueTemp; TerminalExpression term, term1, term2; Expression exp; /** ALGORITMA **/ printQueue(this.expressionPostfixQueue); operationStack = new Stack <TerminalExpression>(); while (this.expressionPostfixQueue.Count != 0) { queueTemp = this.expressionPostfixQueue.Dequeue(); if (queueTemp.GetItem1() == "#") { term = new TerminalExpression(queueTemp.GetItem2()); operationStack.Push(term); Console.WriteLine(queueTemp.GetItem2()); } else { switch (queueTemp.GetItem1()) { case "+": term2 = operationStack.Pop(); term1 = operationStack.Pop(); exp = new AddExpression(term1, term2); term = new TerminalExpression(exp.solve()); operationStack.Push(term); break; case "-": term2 = operationStack.Pop(); term1 = operationStack.Pop(); exp = new SubstractExpression(term1, term2); term = new TerminalExpression(exp.solve()); operationStack.Push(term); break; case "*": term2 = operationStack.Pop(); term1 = operationStack.Pop(); exp = new MultiplyExpression(term1, term2); term = new TerminalExpression(exp.solve()); operationStack.Push(term); break; case "/": term2 = operationStack.Pop(); term1 = operationStack.Pop(); exp = new DivideExpression(term1, term2); term = new TerminalExpression(exp.solve()); operationStack.Push(term); break; case "akar": term1 = operationStack.Pop(); exp = new RootExpression(term1); term = new TerminalExpression(exp.solve()); operationStack.Push(term); break; } } } term = operationStack.Pop(); return(term.solve()); }
private void buttonResult_onClick(object sender, EventArgs e) { int i = 0; string ekspresi = labelScreen.Text; double ans; TerminalExpression ansNow; TerminalExpression operandWithClass; ansNow = new TerminalExpression(); //double ansNow = 0; StringBuilder ekspresi1 = new StringBuilder(); if (ekspresi.Length == 0) { labelScreen.Text = "Error: Nothing inside"; isError = true; } else { double operand; try { while (i < ekspresi.Length) { if (ekspresi[i] == '-' && ekspresi[i + 1] != ' ') { unaryOp = '-'; } else if (ekspresi[i] == '+' || ekspresi[i] == '-' || ekspresi[i] == '*' || ekspresi[i] == '÷') { operand = double.Parse(ekspresi1.ToString(), System.Globalization.CultureInfo.InvariantCulture); TerminalExpression transition = new TerminalExpression(operand); if (unaryOp == '-') { NegativeExpression <double> negative = new NegativeExpression <double>(transition); ansNow.setX(negative.solve()); unaryOp = ' '; } else { ansNow.setX(operand); } op = ekspresi[i]; ekspresi1.Clear(); } else if (ekspresi[i] == '√') { unaryOp = '√'; } else { ekspresi1.Append(ekspresi[i]); } i++; } operand = double.Parse(ekspresi1.ToString(), System.Globalization.CultureInfo.InvariantCulture); if (unaryOp == '-') { operand = operand * -1; unaryOp = ' '; } operandWithClass = new TerminalExpression(operand); if (unaryOp == '√') { ans = CalculateUnary(operandWithClass); //operand = Math.Sqrt(operand); unaryOp = ' '; } else if (op == ' ') { ans = operand; } else { ans = CalculateBinary(ansNow, operandWithClass); } ans = Math.Round(ans, 5); labelScreen.Text = ans.ToString(System.Globalization.CultureInfo.InvariantCulture); lastStrNumber = ans.ToString(System.Globalization.CultureInfo.InvariantCulture); isDecimal = false; isNegative = false; numberDecimal.Clear(); isOpInLast = false; isRoot = false; isOneOp = false; nilaiAnswer = double.Parse(ans.ToString(System.Globalization.CultureInfo.InvariantCulture), System.Globalization.CultureInfo.InvariantCulture); isAnswer = true; hasAnswer = true; bool hasKoma = false; int temp = 0; while ((temp < labelScreen.Text.Length) && (!hasKoma)) { if (labelScreen.Text[temp] == '.') { hasKoma = true; } else { temp++; } } if (hasKoma) { isDecimal = true; } op = ' '; } catch (Error a) { clearData(); isError = true; op = ' '; labelScreen.Text = a.printMessage(); } } isDecimal = true; }
private double CalculateUnary(TerminalExpression a) { RootExpression <double> hasil = new RootExpression <double>(a); return(hasil.solve()); }
public virtual void Visit <TType>(TerminalExpression <TType, TContext> expression) { }