Thread to evaluate arithmetic expressions

I'm trying to write a program that evalutaes arithmetic expression concurrently using Java concurency primitives. The idea behind the threading is to avoid multiple evaluations of common subexpression. I have attached the code that I have written so far but was hoping someone could offer me a hand with the evaluate() and run() methods contained at the end of the program. Thanks.
public class Example {
     public static void main(String[] args) {
          BinaryOp plus = new BinaryOp() {
               public int apply(int n1, int n2) {
                    return n1 + n2;
          BinaryOp times = new BinaryOp() {
               public int apply(int n1, int n2) {
                    return n1 * n2;
          Arith e1 = new Operator(plus, new Number(4), new Number(5));
          Arith e2 = new Operator(plus,new Operator(times, new Number(3), e1),
               new Operator(plus, e1, new Number(6)));
          Arith e3 = new Operator(times, e2, e2);
          System.out.println(e3.evaluate());
interface BinaryOp {
     // An operator that can be applied to two numbers
     int apply(int n1, int n2);
interface Arith {
     // An arithmetic expression that can be evaluated.
     int evaluate();
class Number implements Arith {
     private int n;
     Number(int n) {
          this.n = n;
     public int evaluate() { // A number evaluates to itself.
          return n;
class Operator implements Arith, Runnable {
     private BinaryOp op;
     private Arith e1;
     private Arith e2;
     private boolean done = false;
     private int result = 0; // holds the result of previous evaluation
     Operator(BinaryOp op, Arith e1, Arith e2) {
          this.op = op;
          this.e1 = e1;
          this.e2 = e2;
          (new Thread(this)).start();
     public int evaluate() {
     public void run() {
}

I'm trying to write a program that evalutaes arithmetic expression
concurrently using Java concurency primitives. The idea behind the
threading is to avoid multiple evaluations of common subexpression. Interesting ... the main problem however is to find those common
subexpressions. Most of the evaluation of those common subexpressions
can be done in the parse/compile phase though, effectively elliminating
the need for threads, e.g. (foo+bar)-(foo+bar) can be deduced to be
equal to zero if both 'foo' and 'bar' happen to referential transparent,
i.e. they don't have side effects.
What you're doing now is just starting a new thread for every binary operator.
This is, most likely, not what you want. The strategy of what thread to
start for which subexpression must have layed out the sequence of
threads to start before actual evaluation is started (also see above).
kind regards,
Jos

Similar Messages

  • Need help regarding Arithmetic Expressions

    Hi Experts,
    I have a requirement where in I need to pass Arithmetic Expressions (+,-,/) as constants to a subroutine.For ex:
    constants:c_p   type char1 value '+',
                     c_m   type char1 value '-',
    data:v_a type char1 value '2',
             v_b type char1 value '6',
            v_r    type string.
    v_r = v_ a   + v_b.
    In the above instead of + I want use c_p.Please help me out is there any other way in defining Arithmetic expresiions where I could use constants or variables instead of directly using these expressions(+,-).Thanks in advance.
    With Regards,
    Srini..

    Hello Srini,
    I think you must have a look at the FMs belonging to FuGr. CALC.
    For e.g.,  EVAL_FORMULA which evaluates Literal or Variable formulas
    CONSTANTS:
    C_P TYPE CHAR1 VALUE '+',
    C_M TYPE CHAR1 VALUE '-'.
    DATA:
    V_A TYPE CHAR1 VALUE '2',
    V_B TYPE CHAR1 VALUE '6',
    V_FORMULA TYPE STRING,
    V_RES_F   TYPE F,
    V_RES_P   TYPE P.
    CONCATENATE V_A C_P V_B INTO V_FORMULA SEPARATED BY SPACE.
    CALL FUNCTION 'EVAL_FORMULA'
      EXPORTING
        FORMULA                 = V_FORMULA
      IMPORTING
        VALUE                   = V_RES_F
      EXCEPTIONS
        DIVISION_BY_ZERO        = 1
        EXP_ERROR               = 2
        FORMULA_TABLE_NOT_VALID = 3
        INVALID_EXPRESSION      = 4
        INVALID_VALUE           = 5
        LOG_ERROR               = 6
        PARAMETER_ERROR         = 7
        SQRT_ERROR              = 8
        UNITS_NOT_VALID         = 9
        MISSING_PARAMETER       = 10
        OTHERS                  = 11.
    IF SY-SUBRC = 0.
      MOVE V_RES_F TO V_RES_P.
      WRITE: V_RES_P .
    ENDIF.
    BR,
    Suhas

  • Evaluate math expression

    Hi Guys,
    I need to write java command line program to evaluate a mathematical
    expression input by user without parantheses using Stack approach.
    Can anyone give me the clue how to start of with.
    Is it possible to evaluate the expression in infix notation directly using stack, without converting to prefix notation.
    Thanks in advance

    Is there something nicer?You can also use java 6 and javascripts. I saw a
    thread where someone posted an example.
    KajI posted something a couple of weeks back (reply #2):
    http://forum.java.sun.com/thread.jspa?threadID=5137192
    Of course, you don't need to bind any variables and can do it like this:import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    public class ScriptDemo {
        public static void main(String[] args) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            try {
                String expression = "3+4";
                Object result = engine.eval(expression);
                System.out.println(expression+" = "+result);
            } catch(ScriptException se) {
                se.printStackTrace();
        output: 3+4 = 7.0
    */

  • Fully parentized arithmetic expression

    Hi,
    Would any one be able to tell how does following fully parentized arithmetic expression turns 28?
    I don't get it.
    As an example of using identifiers and assignment, consider the FPAE
    (x0 = ((3 + (x1 = 4)) * x1))
    This expression evaluates to 28 and has the side effects of making the values associated to x0 and x1 28 and 4, respectively. Hence, if the next FPAE to be evaluated were
    (x1 = (x0 - x1))
    the result would be 28 - 4, or 24, and, as a side effect, the value of x1 would be changed to 24. The intent, then, is for identifiers to retain their values (or to have them changed, via assignment) as evaluation continues from one FPAE to another.
    Thanks

    (x0 = ((3 + (x1 = 4)) * x1))
    3+(x1=4)At this point x1 = 4 so the value is 7.
    (3+(x1=4))*x1x1 is still 4, so 7 x 4 = 28.
    Operands are evaluated strictly left to right.

  • "ABAP Basics" Book - arithmetic expression error in the sample code

    Hi all,
    I have just started learning ABAP on mini SAP system (NW7.01) by following "ABAP Basics" book.
    This question might be a FAQ, but I have spent a few days searching a right answer without success.
    I appreciate if you could help me on this.
    On the page 162, there is a function module sample, which contains the line as following:
    e_amount = i_km * '0.3'.
    Here l_km (import) is type of i, and e_amount (export) is type of f.
    Though I do not think of any problem with this line, it throws an arithmetic expression error when executed directly for testing as well as when called from a program.
    When I tried a similar thing in a program, it was fine.
    However within a function module it throws this error.
    Thanks in advance.
    Terry

    Like I said before, I do not think any problem about the code itself.
    I suspect some environmental things?
    I should have mentioned SAP mini system NW7.01 is running on Vista Business?
    To be specifc, I receive this message:
    Arithmetic operations are only expected for operands that can be converted to numbers.
    (numeric operands). - (numeric operands). - - - -
    with the following function module:
    [code]
    FUNCTION ZPTB00_CALCULATE_TRAVEL_EXPENS.
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(I_KM) TYPE REF TO  I
    *"  EXPORTING
    *"     VALUE(E_AMOUNT) TYPE REF TO  F
    *"  EXCEPTIONS
    *"      FAILED
    e_amount = i_km * '0.3'.
    IF sy-subrc <> 0.
      RAISE failed.
    ENDIF.
    ENDFUNCTION.
    [/code]

  • Regular expressions to parse arithmetic expression

    Hello,
    I would like to parse arithmetic expressions like the following
    "5.2 + cos($PI/2) * -5"where valid expression entities are numbers, operations, variables and paranthesis. Until now I have figured out some regular expressions to match every type of entities that I need, and combine them into one big regex supplied to a pattern and matcher. I will paste some code now to see what I wrote:
    public class RegexTest {
        /** A regular expression matching numeric expressions (floating point numbers) */
        private static final String REGEX_NUMERIC = "(-?[0-9]+([0-9]*|[\\.]?[0-9]+))";
        /** A regular expression matching a valid variable name */
        private static final String REGEX_VARIABLE = "(\\$[a-zA-Z][a-zA-Z0-9]*)";
        /** A regular expression matching a valid operation string */
        public static final String REGEX_OPERATION = "(([a-zA-Z][a-zA-Z0-9]+)|([\\*\\/\\+\\-\\|\\?\\:\\@\\&\\^<>'`=%#]{1,2}))";
        /** A regular expression matching a valid paranthesis */
        private static final String REGEX_PARANTHESIS = "([\\(\\)])";
        public static void main(String[] args) {
            String s = "5.2 + cos($PI/2) * -5".replaceAll(" ", "");
            Pattern p = Pattern.compile(REGEX_OPERATION + "|" + REGEX_NUMERIC + "|" + REGEX_VARIABLE + "|" + REGEX_PARANTHESIS);
            Matcher m = p.matcher(s);
            while (m.find()) {
                System.out.println(m.group());
    }The output is
    5
    2
    +
    cos
    $PI
    2
    5There are a few problems:
    1. It splits "5.2" into "5" and "2" instead of keeping it together (so there might pe a problem with REGEX_NUMERIC although "5.2".matches(REGEX_NUMERIC) returns true)
    2. It interprets "... * -5" as the operation " *- " and the number "5" instead of " * " and "-5".
    Any solution to solve these 2 problems are greately appreciated. Thank you in advance.
    Radu Cosmin.

    cosminr wrote:
    So, I've written some concludent examples and the output after parsing (separated by " , " ):
    String e1 = "abs(-5) + -3";
    // output now: abs , ( , - , 5 , ) , + , - , 3 ,
    // should be:  abs , ( , -5 , ) , + , - , 3 , (Notice the -5)
    I presume that should also be "-3" instead of ["-", "3"].
    String e2 = "sqrt(abs($x=1 + -10))";
    // output now: sqrt , ( , abs , ( , $x , = , 1 , + , - , 10 , ) , ) ,
    // should be:  sqrt , ( , abs , ( , $x , = , 1 , + , -10 , ) , ) ,   (Notice the -10)
    String e3 = "$e * -1 + (2 - sqrt(4))";
    // output now: $e , * , - , 1 , + , ( , 2 , - , sqrt , ( , 4 , ) , ) ,
    // should be:  $e , * , -1 , + , ( , 2 , - , sqrt , ( , 4 , ) , ) ,
    String e4 = "sin($PI/4) - 3";
    // output now: sin , ( , $PI , / , 4 , ) , - , 3 , (This one is correct)
    String e5 = "sin($PI/4) - -3 - (-4)";
    // output now: sin , ( , $PI , / , 4 , ) , - , - , 3 , - , ( , - , 4 , ) ,
    // should be:  sin , ( , $PI , / , 4 , ) , - , -3 , - , ( , -4 , ) ,  (Notice -3 and -4)I hope they are relevant, If not I will supply some more.I made a small change to REGEX_NUMERIC and also put REGEX_NUMERIC at the start of the "complete pattern" when the Matcher is created:
    import java.util.regex.*;
    class Test {
        private static final String REGEX_NUMERIC = "(((?<=[-+*/(])|(?<=^))-)?\\d+(\\.\\d+)?";
        private static final String REGEX_VARIABLE = "\\$[a-zA-Z][a-zA-Z0-9]*";
        public static final String REGEX_OPERATION = "[a-zA-Z][a-zA-Z0-9]+|[-*/+|?:@&^<>'`=%#]";
        private static final String REGEX_PARANTHESIS = "[()]";
        public static void main(String[] args) {
            String[] tests = {
                "abs(-5) + -3",
                "sqrt(abs($x=1 + -10))",
                "$e * -1 + (2 - sqrt(4))",
                "sin($PI/4) - 3",
                "sin($PI/4) - -3 - (-4)",
                "-2-4" // minus sign at the start of the expression
            Pattern p = Pattern.compile(REGEX_NUMERIC + "|" + REGEX_OPERATION + "|" + REGEX_VARIABLE + "|" + REGEX_PARANTHESIS);
            for(String s: tests) {
                s = s.replaceAll("\\s", "");
                Matcher m = p.matcher(s);
                System.out.printf("%-21s-->", s);
                while (m.find()) {
                    System.out.printf("%6s", m.group());
                System.out.println();
    }Note that since Java's regex engine does not support "variable length look behinds", you will need to remove the white spaces from your expression, otherwise REGEX_NUMERIC will go wrong if a String looks like this:
    "1 - - 1"Good luck!

  • Add spaces in arithmetic expressions

    Hi experts,
    i have to insert spaces in arithmetical expressions written by users.
    For example:
    INPUT (by USERS): A+B-SQRT(C)/(D**2)
    OUTPUT (by Program): A + B - SQRT( C ) / ( D ** 2 )
    Possible arithmetic operators are:
    +; - ; *; /; **; SQRT()
    Any hints will be rewarded.
    Thanks in advance.
    Fabio.

    Thanks to all guys!
    the right code is a mixt of yours hints:
      l_len = STRLEN( tb_mzcatc-/bic/zformatc ).
      DO.
        l_char = input+n(1).
        CASE l_char.
          WHEN 'Q' OR
               'R'.
            CONCATENATE formula l_char INTO formula.
          WHEN 'T'.
            l_char = input+n(2).
            CONCATENATE formula l_char INTO formula.
            n = n + 1.
          WHEN '*'.
            IF input+n(2) = '**'.
              l_char = input+n(2).
              CONCATENATE formula l_char INTO formula SEPARATED BY ' '.
              n = n + 1.
            ELSE.
              CONCATENATE formula l_char INTO formula SEPARATED BY ' '.
            ENDIF.
          WHEN OTHERS.
            CONCATENATE formula l_char INTO formula SEPARATED BY ' '.
        ENDCASE.
        n = n + 1.
        IF n GT l_len.
          EXIT.
        ENDIF.
      ENDDO.
    Message was edited by:
            Fabio Cappabianca

  • Evaluate String Expression

    Hi all,
    I am trying to evaluate a string expression against rows of data. If the data satisfys that condition/expression then its selected otherwirse its not.
    To re-iterate how to evaluate a string expression like: "value < 1"
    against data values like: 0, 1, 2 ...n
    Any help will be appreciated. Thanks in advance.
    Here's the code I am using:
          * Evaluates the Expression Either return True or False
          * @return
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                                            // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                                  Boolean condition = new Boolean(pc.getExpression());
                                                      // Evaluate the expression against the data elements
                             if (condition.booleanValue()) {
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

    ProcessCondion holds the Expression but I need to match the value the expression matches.
    A bit like equals example I am trying out now:
      public boolean evalExpression() {
              boolean retval = true;
              // Identify the conditional process step
              if (this.isConditional()) {
                   // get the inputs
                   for (int i = 0; i < myInputs.size(); i++) {
                        ContainerDataElement containerDataElement = (ContainerDataElement) myInputs
                                  .elementAt(i);
                        String data = containerDataElement.getValueAsString();
                        com.aim.common.DebugLog.debug("dataELEMENTS--------"
                                  + data.toString());
                        // Get the conditions
                        for (int j = 0; j < myProcessConditions.size(); j++) {
                             ProcessCondition pc = (ProcessCondition) myProcessConditions
                                       .elementAt(j);
                             com.aim.common.DebugLog.debug("ProcessCondition--------"
                                       + pc.toString());
                             Boolean condition = new Boolean(pc.getExpression());
                             com.aim.common.DebugLog.debug("condition--------"
                                       + condition.toString());
                             // Evaluate the expression against the data elements
                             if (containerDataElement.equals(condition)) {
                                  com.aim.common.DebugLog.debug("conditionEVALUATED--------"
                                            + retval);
                                  retval = true;
                             else {
                                  retval = false;
              return retval;
         }

  • Regex for arithmetic expressions

    Hi all,
    I am new to Java. I was wondering if anyone can help me understand how regular expressions work. My problem is how to come up with a regular expression that would match a simple arithmetic expression like:
    a + b + c + d
    And I want to capture things by groups. I largely suspect that I should use something like:
    (\\w+)(\\s\\+\\s(\\w+))*
    (I use the \\s here because \\b doesn't seem to work)
    would work by capturing the first word like sequence with (\\w+), and the succeeding repeats of the plus sign and another word being captured by (\\s\\+\\s(\\w+))*. Didn't work though. Can anyone tell me what's wrong and how to think of a better way of handling these sort of expressions?
    The code I tried goes like:
    String patt = "(\\w+)(\\s\\+\\s(\\w+))*";
    String feed = "a + b + c + d";
    Pattern p = Pattern.compile(patt);
    Matcher m = p.matcher(feed);
    /* here I want to see if the groupings work somehow*/
    if(m.find()){
    for(int i=0; i<=m.groupCount(); i++)
    System.out.println(m.group(i));
    Thanks

    Sorry about that. Here's the correctly formatted post:
    So, with a simple arithmetic expression like:
    a + b + c + dI want to capture things by groups and I thought of using something like:
    (\\w+)(\\s\\+\\s(\\w+))*(I use the \\s here because \\b doesn't seem to work)
    with the idea of capturing the first word like sequence with (\\w+), and the succeeding repeats of the plus sign and another word being captured by (\\s\\+\\s(\\w+))*. As this didn't work, can anyone tell me what's wrong and how to think of a better way of handling these sort of expressions?
    The code I tried goes like:
    String patt = "(\\w+)(\\s\\+\\s(\\w+))*";
    String feed = "a + b + c + d";
    Pattern p = Pattern.compile(patt);
    Matcher m = p.matcher(feed);then I want to see if the groupings work somehow
    if(m.find()){
    for(int i=0; i<=m.groupCount(); i++)
    System.out.println(m.group(i));
    }and yes, I am wondering if arithmetic parsing would be possible with regex. I have implemented something similar before using combinations of simple tokenization and character checks, but I want to make cleaner looking code. Would using regular expressions be a bad choice? What if I feed something like:
    (a + b) + (c + d)

  • The Expression Engine failed to evaluate the expression for a Subportal Act

    Anyone seen this error before and know of a fix? We're getting it on our 6.1 MP1 portal after we deployed our custom sso solution.
    "62     12-19-2007     12:58:37.292     Error     Portal_UI_Infrastructure     portal.c27mynrspaxr01.webadm     .NET #32     com.plumtree.portaluiinfrastructure.condition.ConditionTypeManager     The Expression Engine failed to evaluate the expression for a Subportal Action.
    System.NullReferenceException: Object reference not set to an instance of an object.
    at com.plumtree.portaluiinfrastructure.condition.ConditionTypeManager.EvaluateExpressionForSubportalAction(AActivitySpace asCurrentSpace, IApplication application, IXPRequest xpRequest, Object ptUserSession) in e:\buildroot\Release\portalui\6.1.x\ptwebui\portaluiinfrastructure\dotnet\prod\src\com\plumtree\portaluiinfrastructure\condition\ConditionTypeManager.cs:line 260 <ptLogMsgEnd>"

    As far as i know this is a harmless error. Our portal generated that message every time someone browsed /portal/server.pt.

  • Arithmetic Expression validation

    Can somebody help me in giving me a java program which can
    validate an arithmetic expression.
    For eg ( A + b1 ) / (2 * c) + d
    If someone already has a code snippet which takes an expression String
    and returns a boolean which tells if the expression is valid or not, please post it..... My project is running out of coding time :))))

    With due respect....Its not the question of not trying
    it.. I just thought it would not be judicious to
    re-invent the wheel. Depends on what you are doing.
    If you are working in industry, or are doing a final year project, code re-use is an excellent time saver.
    If you are doing homework which asks you to write an equation validator, code re-use is pretty much cheating. If you did this, you might as welll let the brightets person in the class write the code, and everyone else hand in the same code.

  • Arithmetic expression performance

    Hi,
    Is there any difference in arithmetic expression evaluation performance between one big expression and several smaller that save their partial results in variables?
    For example: Which solution will work faster:
    1)
    int i;
    for(i=1000000; i>=0; i--)
      x=i*a+b*c; //a, b, c - some variables
    }2) int i,p1, p2;
    for(i=1000000; i>=0; i--)
    //a, b, c - some variables
    p1 = i*a;
    p2 = b*c;
    x[i] = p1+p2;

    I some cases I can replace a division with a multiplication.
    Instead of:
    for(int i=0; i<1000; i++)
      tab=tab[i]/5;
    }I can use:int scale = (1<<16)/5;
    for(int i=0; i<1000; i++)
    tab[i]=(tab[i] * scale)>>16;
    }The second solution gives the same result and avoids division by replacing it with multiplication and very fast bit shift operation.
    I can see that my problem is wider that I  thought. Processor manuals are quite precise, but I'm programming in java, not in assebler. So most important issue for me is the way the JVM implementation will execute each bytecode operation. I think that various JVM for various platforms may execute instructions differently. So I'm looking for general tips which operations should be avoided when performance is the key issue.
    I'm writing image processing aplication for mobile devices, so any milisecond counts for me.
    I found some java performance tips on the inernet, but, frankly, I don't trust them. For example: It is recommended to avoid 2-dimensional tables and implement them as 1D table. So instead of:int[][] tab = new int[100][100];
    tab[x][y] = c;one should use:int[] tab = new int[10000];
    tab[y*100+x]=c;It seems reasonable, but the second solution needs multiplication. In the first solution compiler can generate code that store pointers to "second dimension tables" in "first dimension" (table with references to tables). Pointers (references, i mean) have size of 2^n. Integers in second dimension are also of size 2^n. So theoretically compiler may produce byte code that will need no multiplication but only very fast bit-shift operations.
    My question is - how does the compiler cope with 2d arrays.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Parsing an arithmetic expression

    Hi,
    I'd like to get the result of an arithmetic expression. I found some algorithms which describe how to get the result of an expression with parens and the four basic operations (+, -, *, /). Now I want to do this to an expression with all the operations you can find on a scientific calculator, for example sin, cos, log, ^, sqrt, nCr, ! ...
    I mean something like this:
    sin(2x)*sqrt(8.5x/1.25)+5/x^3-x^(2-5x)-5!
    The algorithm would have to return -123.1322 in this case.
    Does anyone know how normal calculators does this? I am more interested in the basic idea and not the coding itself.
    I thought about something like this:
    solve(expression)
       do until there is a result:
          if there are no other operations in the expression than +, -, *,/ and parens, then:
             calculate the result and return it
          else:
             search the first operation which is not +, -, * or / , for example sin(...)
             get the caption in the brackets
             solve(caption in the brackets)      <--- recursive functionDo you have a better idea? I am nor sure this is a good algorithm.
    DrummerB
    Edited by: DrummerB on Feb 28, 2008 5:30 PM

    Hello DrummerB,
    I reckon that without getting into the theory (which I recommend), the simplest way to achieve the goal is using cascading.
    1. Order all operations by precedence, example:
    operators | precedence
         +, - | 0
         *, / | 1
            ! | 2
            - | 3 (unary minus)2. Create a parsing/solving algorithm, example:
    solveExpr(e)
        ts := token stream for e
        return solveAdditiveExpr(ts)
    solveAdditiveExpr(ts)
        left := solveMultiplicativeExpr(ts)
        while next token in ts is "+" or "-"
            right := solveMultiplicativeExpr(ts)
            if next token in ts is "+"
                left := left + right
            else
                left := left - right
            consume next token in ts
        return left
    solveMultiplicativeExpr(ts)
        left := solveFacultyExpr(ts)
        while next token in ts is "*" or "/"
            right := solveFacultyExpr(ts)
            if next token in ts is "*"
                left := left * right
            else
                left := left / right
            consume next token in ts
        return left
    solveFacultyExpr(ts)
        left := solveUnaryMinusExpr(ts)
        while next token in ts is "!"
            left := faculty of left
            consume next token in ts
        return left
    solveUnaryMinusExpr(ts)
        negative := false
        while next token in ts is "-"
            negative := !negative
            consume next token in ts
        if negative
            return -number(ts)
        else
            return number(ts)
    number(ts)
        the next token in ts must be a number, consume and return itExample:
    e := "10 + -5 / 3 * 5! - - - - -7"
    => ts := <10, "+", "-", 5, "/", 3, "*", 5, "!", "-", "-", "-", "-", "-", 7>
    solveExpr(e) = (10 + (((-5) / 3) * (5!))) - 7 = -197With kind regards
    Ben

  • Not showing error in dual while using it as arithmetic expression

    Hi,
    I have a requirement to throw error if two consecutive numbers or two consecutive operators are given. For this I would like to use dual table.
    It is throwing error if two numbers are given, but not throwing error if it has two operators.
    Error thrown for -> select 2 4 - 7 from dual;
    Error not thrown for -> select 2 + - 7 from dual;
    or
    select 2 - + 7 from dual;
    I am expecting an error in later case too. Can we do any changes to the query to throw the error?
    Thanks!

    Hi,
    If str is a string, then this expression
    REGEXP_LIKE ( str
             , '(\d\s+\d)'     || -- digits, separated by 1 or more whitespace characters
               '|'          || -- or
               '([+*/-]\s*[+*/-]'   -- operators, separated by 0 or more whitespace characters
             )will return TRUE if (and only if) str contains either two consecutive digits (separated by at least 1 space character) or str contains two consectuive arithmetic operators (not necessaily separated by space characters).
    You can include other operator symbols, by including them in both of the lists enclosed in square brackets. The hyphen ('-') must be the very first character or the very last character in the list; aside from that, the order of the symbols makes no difference.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using.
    See the forum FAQ {message:id=9360002}

  • Using expression trees to evaluate an expression

    i have a three parameters like age, sex and location. Now, my users while registration, can specify an expression like, age > 25 and age < 30 and sex = male OR location = 'London'. Now i get an incoming request which has certain values for age, sex and location (say: age=26 sex = male location = 'London'). Then i want to get a list of all the users registered with me who satisfies the incoming criteria. Do you think an expression tree would help me in this case? can pls someone guide me?

    actually i have a fixed list of operators and operands. The only variation being that users while registration might use only a subset of those operators and operands e.g. some users may just give an expression such as 'sex=male' and some other users could give an expression such as 'sex = female AND age > 21'. So when i get an incoming request saying sex = female and age = 22 then only my second kind of users would be selected and suppose if i get an incoming message like sex = male , age = 33 then my first kind of users (though no age is specified by that user while registration but still he would be selected as the expression said sex = male and that is one of the parameters of the incoming request) would be selected. Now how do i create such a solution using an expression tree, which would evaluate the incoming request and then match it with the expression specified by the various users to find the list of those users who qualify according to the incoming request parameters. any ideas??

Maybe you are looking for

  • Deleting individual messages in iMessage.

    Does anyone know how to delete individual messages in iMessage. Just updated to ios8 and have lost the function on my iPhone 5s

  • Showing Fields

    please see this image: http://i1104.photobucket.com/albums/h336/809836724/sd/columns.jpg I am using SE16 on this. How can I make the columns (with DATA) appear? How to choose those columns (with data) without manually checking each column? thanks.

  • Can Adobe Reader damage MacBook Air?

    Can Adobe Reader damage MacBook Air?

  • Can't sync transfer fotos from PC to iPad mini

    Hello. I never thought that it's so hard to put my photos from PC to my iPad mini. I have about 200 photos from my work in a folder. And they were successfully transferred to iPad. Recently I added about 50 new photos into a folder and tried to trans

  • Error: ... can not be converted to a unique application ID.

    Full Error: Error     The application alias "<APPLICATION NAME>" can not be converted to a unique application ID. Contact your application administrator. <APPLICATION NAME> -> name of the application. Screenshot: Link Once the application is run from