Code Examples
A repository of 155 code examples for BeepBeep
ArithmeticBuilderPop.java
1 /*
2  BeepBeep, an event stream processor
3  Copyright (C) 2008-2018 Sylvain HallĂ©
4 
5  This program is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published
7  by the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package dsl;
19 
20 import ca.uqac.lif.bullwinkle.BnfParser.InvalidGrammarException;
21 import ca.uqac.lif.bullwinkle.Builds;
22 import ca.uqac.lif.cep.dsl.GrammarObjectBuilder;
23 import ca.uqac.lif.cep.functions.Constant;
24 import ca.uqac.lif.cep.functions.Function;
25 import ca.uqac.lif.cep.functions.FunctionTree;
26 import ca.uqac.lif.cep.util.Numbers;
27 
28 /**
29  * Use a {@link ca.uqac.lif.cep.dsl.GrammarObjectBuilder GrammarObjectBuilder}
30  * to parse and evaluate a string in Polish notation.
31  * @author Sylvain HallĂ©
32  * @difficulty Medium
33  */
34 public class ArithmeticBuilderPop extends GrammarObjectBuilder<Function>
35 {
36  public static void main(String[] args) throws BuildException
37  {
38  //&
40  Function f = builder.build("+ 3 - 4 5");
41  Object[] value = new Object[1];
42  f.evaluate(new Object[]{}, value);
43  System.out.println(value[0]);
44  //&
45  }
46 
47  ///
48  public ArithmeticBuilderPop()
49  {
50  super();
51  try
52  {
53  setGrammar("<exp> := <add> | <sbt> | <num>;\n"
54  + "<add> := + <exp> <exp>;\n"
55  + "<sbt> := - <exp> <exp>;\n"
56  + "<num> := ^[0-9]+;");
57  }
58  catch (InvalidGrammarException e)
59  {
60  // Do nothing
61  }
62  }
63  ///
64 
65  //*
66  @Builds(rule="<num>", pop=true)
67  public Constant handleNum(Object ... parts)
68  {
69  return new Constant(Float.parseFloat((String) parts[0]));
70  }
71  //*
72 
73  //%
74  @Builds(rule="<add>", pop=true)
75  public FunctionTree handleAdd(Object ... parts)
76  {
77  return new FunctionTree(Numbers.addition,
78  (Function) parts[1], (Function) parts[2]);
79  }
80  //%
81 
82  //!
83  @Builds(rule="<sbt>", pop=true)
84  public FunctionTree handleSbt(Object ... parts)
85  {
86  return new FunctionTree(Numbers.subtraction,
87  (Function) parts[1], (Function) parts[2]);
88  }
89  //!
90 
91 }
Use a GrammarObjectBuilder to parse and evaluate a string in Polish notation.