# Analysing a String to call functions

• 02-23-2013, 10:54 PM
tomtaila
Analysing a String to call functions
I was wondering what is the best way to analyse a string and perform functions from it. I'm not sure what the technique itself is actually called so I'll give an example:

Given the parse tree:

+
/\
+ 2
/\
3 2

Which represents the function: (3+2)+2 = 7

I have managed to obtain the following String to represent the functionality: "++322"

My question is what is the best way to take strings like this and derive the functionality they represent? Any resources to help with this problem would be a massive help, thanks!
• 02-23-2013, 11:13 PM
jim829
Re: Analysing a String to call functions
Well, I might do it differently. Given your parse tree I would do a post-order traversal of the tree (left node, right node, root) and get
32+2+. This is then in Reverse Polish Notation.. Then I would simply implement a stack, pushing the tokens on as I get them. As soon as I see an operator, I would apply the operator to the top two stack elements and push the result back on the stack. Then just keep repeating the process.

Other approaches may also work.

Regards,
Jim
• 02-26-2013, 12:20 AM
jim829
Re: Analysing a String to call functions
After some thought I don't believe I answered your original question. It sounds like what you want is a function array where each element represents a different function. In my experience these are referred to as function tables.

One way to do this would be to use a HashMap to have operators hash to the correct function.

Code:

interface Operation {
public double compute(double a, double b);
}

public class Example {

public static void main(String[] args) {
Map<String, Operation> Ops = new HashMap<>();
Ops.put("+", new Operation() {
public double compute(double a, double b) {
return a + b;
}
});
Ops.put("*", new Operation() {
public double compute(double a, double b) {
return a * b;
}
});
String op = "*";
System.out.println(Ops.get(op).compute(10, 20)); // should print 200
}
}

To make the code simpler I didn't use generics (otherwise the compiler would complain about passing 10 and 20 to Doubles). This is essentially using the Strategy based design pattern. Also, as of Java 1.7, you can switch on string values in case statements.

Jim