Quote:

>> >> Ah, but what if the RPN is of the form?

>> >> (2 3 + 5 /)

>> >Then obviously you'll need something external that tells you the arity

>> >of what you're currently looking at:

>> >number -> arity 0

>> >constant (e.g. pi) -> arity 0

>> >"+/-" -> arity 1

>> >"+" -> arity 2

>> >Then you just chop off the list as many operands as required --

>> >recursively, of course :-)

>> That was my first thought, and I did write a short and very simple function

>> that did exactly that. I intended to post it, but then it occured to me that

>> the arguments don't really have to be in the right order. For instance, you

>> might have (1 2 3 * +) = 7. A stack based approach would handle it easily,

>> the list chopping method would croak.

>You thought of the list chopping method because you were thinking like

>a human and not like a computer. IOW, you were looking at your

>potential data set, in this case

> (1 2 3 * +)

>and saw it all at once on the screen. A computer doesn't see things

>in a gestalt form though, it sees them as individual datums, one at a

>time.

>[(] [1] [2] [3] [*] [+] [)]

>If you teach yourself to think like this more often you'll find that

>your original solutions are much closer to the optimal way of doing

>things on a computer. This took me a couple of years to notice long,

>long ago, but since then the idea of seeing things only one datum at a

>time has served me well.

I hope this wasn't meant for me? I have been programming for 11 years, and I

think I would know fairly well by now how to reason about how the computer

interprets data.

Quote:

>Keep two temporary variables for storage, then pop numbers off the

>stack into them. Then pop an operator off.

This won't work for precisely the reason I mentioned. You may not have an

operator immediately following two numbers. You have to go through the list

and push every number on the stack. When you get to an operator you pop the

two last numbers off the stack, apply the operator, and push the result back

on and continue going through the list.

If you want to assume that all operators are binary and that two numbers are

always followed by an operator you can make a quick and dirty solution:

(define (rpn expr)

(if (null? (cdr expr))

(car expr)

(rpn (cons (eval `(,(caddr expr)

,(car expr)

,(cadr expr)))

(cdddr expr)))

)

)

Quote:

> (rpn '(1 2 + 3 + 4 *))

24

> (rpn '(1 2 / 50 *))

25

--

- t