WIZARDELF
WIZARDELF

Reputation: 3885

parsing arithmetic expression in Scheme

I know how to use stack to process an arithmetic expression string like `(1 + 2) * 3'. Is there a typical Scheme solution to this issue?

Upvotes: 0

Views: 1283

Answers (2)

John Clements
John Clements

Reputation: 17203

It's a little hard to tell what question you're asking. In Scheme (or Racket), you'd almost certainly write such an evaluator "directly", like this:

  • for E1 * E2, return (eval E1) times (eval E2)
  • for E1 + E2, return (eval E1) plus (eval E2)

... so the evaluator is going to be literally three lines long.

Note that in this definition, there's no need to keep track of a stack explicitly (of course, you can do the same thing in any other language--you'd use an explicit stack only if you wanted to write the evaluator in the form of a loop, and didn't want to separate the parsing step).

To parse the expression, you need... well, you probably want a parser. If you're using Racket, you could take a look at the calculator example that comes with Racket in collects/parser-tools/examples/calck.rkt. It handles everything you describe. I could paste it all in here, but that's probably overkill.

Upvotes: 1

erjiang
erjiang

Reputation: 45657

Yes, the Scheme solution is to parse the expression, and then use a stack like you already know how to do.

Upvotes: 0

Related Questions