Wednesday, November 6, 2013

Parsing string to math expression with inline function

This week, I discovered a new math game for Android: Match The Math (https://play.google.com/store/apps/details?id=com.engcross.matchthemath).

I have seen this app converts a string to a math expression and solves it in real-time. So I though about how doing it in Scilab, to get a string like "2*5 + 2" and return the number that corresponds to the result of the expression, in the example 12 (= 2*5 + 2).

Scilab has an interesting way to create "one line" functions, e. g. sum2numbers(a,b) where this function should return just a+b. This way is called inline functions and is defined like following:

deff('[x]=func(a,b)', 'x=a+b');

Where '[x]=func(a,b)' defines the structure of the function with x being the return, func is the name of the function and a and b are the arguments; 'x=a+b' is what the function executes when is called: x=a+b.

With this concept in mind, we can use a inline function to parse a string to a arithmetic expression because deff() uses only strings as arguments.

Let's use a common function definition, with a string to be parsed as argument, and one inline function inside:

function [x]=parsingStr2Arithmetics(s) // definition of the function
deff('[x]=f()', 'x='+s); // creates inline function that parses the string
x = f(); // calls the function to return it result
endfunction; //end of the function



Now our function is ready, we can test it using different expressions as arguments.

-->parsingStr2Arithmetics("2")
 ans  =

    2. 

-->parsingStr2Arithmetics("2+2")
 ans  =

    4. 

-->parsingStr2Arithmetics("2+2*5")
 ans  =

    12. 
-->parsingStr2Arithmetics("(2+2)*5")
 ans  =

    20. 

-->parsingStr2Arithmetics("(2+2)*5 - 3")
 ans  =

    17. 


For finishing this post, I recommend you to try Match The Math game, it's really cool and improves our math and problems solving skills.