I am trying to make a calculator in C or Objective-C that accepts a string along the lines of
8/2+4(3*9)^2
and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?
Dave DeLong's DDMathParser class may save you a lot of time and trouble.
Try this:
http://en.wikipedia.org/wiki/Shunting-yard_algorithm
using Objective-C NSLinguisticTagger may be a good solution
I did this in CSE340: Introduction to Programming Lanugages in my Junior year of CS in college. So if you really want to code up a parser from scratch, be prepared that it could be "a semester long project."
You'll need to tokenize, parse, build an abstract expression tree, evaluate, etc.
We used Louden's Programming Languages: Principles and Practice. I liked it. Though it didn't do the best job of walking you through the implementation process.
Of course, this would be more than "coding up from scratch." You'd need to make a grammar, then build a parser to process the rules...aside from a learning activity, I'm not sure why you'd wanna do this.
The shunting yard algorithm has already been mentioned. The other classic one is simple recursive descent. Here's a fairly short one I wrote many years ago:
Note that this particular one just parses input, and converts it to RPN form. If you want to interpret the result instead, you'd replace printing out each operand/operator with actually evaluating the result of that part of the expression.
I think this close to what you want: http://www.codeproject.com/KB/recipes/alxparser.aspx