I'm working on building an interpreter on top of arduino and its the most interesting and difficult thing I've ever done! One of the most basic features of any programming language is the ability for it to do math. Ive got that down multiplication runs flawlessly even with multiple terms (555) however Im trying to make it so that the arduino understands that a '-' can denote a negative number. and the problem lies with me mentally not understanding how we as humans figure it out.
5*-5
would return 0 as an answer because it would interpret this as 5 multiplied by nothing. because between the * and the next operation - is "/0" 5*null is 0 or null (I think, I dont know if i can still call myself a beginner but I'm learning )
I thought about using parenthesis but this would mean i can use them later for specifying what operations come first "(5+5)*2" returning 20 instead of 15 according to PEMDAS.
in case your curious or need some help with making your own evaluation system here is my function. it currently is only setup for doing multiplication because i wanted to solve the problems of negatives first thing.
//count the amount of functions
for (int i = 0; i < input.length(); i++)
{
switch (input.charAt(i)) {
case '*':
functionCount[0]++;
break;
case '/':
functionCount[1]++;
break;
case '+':
functionCount[2]++;
break;
case '-':
functionCount[3]++;
break;
}
}
// calculate multiplication problems
for (int i = 0; i < functionCount[0]; i++)
{
if(input.indexOf('*') ==-1){break;}
int center = input.indexOf('*');
int endPoint = 0;
int startPoint = 0;
int A = 0;
int B = 0;
for (int j = 0; center - j < input.length(); j++)
{
int calcPoint = center - j - 1;
Serial.println(calcPoint);
if (input.charAt(calcPoint) == '*' || input.charAt(j) == '/' || input.charAt(j) == '+' || input.charAt(j) == '-' || input.charAt(j) == '/0' )
{
Serial.println(input.charAt(calcPoint));
Serial.println(calcPoint);
startPoint = calcPoint;
break;
}
if (calcPoint < 1) {
break;
}
}
Serial.print("start term A is:");
A = input.substring(startPoint, center ).toInt();
Serial.println(input.substring(startPoint, center ).toInt());
Serial.println(startPoint);
Serial.println(center - 1);
for (int j = center + 1; j < input.length(); j++)
{
if (input.charAt(j) == '*' || input.charAt(j) == '/' || input.charAt(j) == '+' || input.charAt(j) == '-' || input.charAt(j) == '/0' )
{
Serial.print(input.charAt(j));
Serial.println(j);
endPoint = j;
break;
}
else {
endPoint = input.length();
}
}
Serial.print("end term B is:");
B = input.substring(center + 1, endPoint).toInt();
Serial.println(input.substring(center + 1, endPoint).toInt());
input.replace(input.substring(startPoint, endPoint), String(A * B));
Serial.println(input);
Serial.println("loop completed");
}
// print the answer as int
Serial.println(input.toInt());
}