Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

K&N Exercise Problem

50 views
Skip to first unread message

Manish Gill

unread,
May 23, 2013, 5:26:02 PM5/23/13
to
I've gotten started with the famous book. As of now, I'm stuck on an exercise in Chapter 4. I would really love if someone could provide some hints as to what I'm doing wrong and how can I improve the solution. The problem wants me to add some improvements (add variables) to the Polish calculator.

Here is what I have so far: http://bpaste.net/show/k1Eb8vDV7nSbOhpbzLDh/

The problem is in the handle_vars function. It's not really working the way I want it to. Something like

10 a
a 3 +

will work, but it gets weird when I introduce another variable.

20 b
40 b +
Error: Stack empty.

I'll appreciate any help.

Thanks.

Bart van Ingen Schenau

unread,
May 26, 2013, 12:29:15 PM5/26/13
to
It is not the `b` variable that trips things up, but the fact that your
calculator treats `40 b` as an assignment.
In common in-fix notation, the failing input is interpreted as:

(b = 20)
(b = 40) + <missing argument>

Your best option to salvage this is to use an explicit symbol for
assignment, so that the example reads

20 b =
40 b +

>
> Thanks.

Bart v Ingen Schenau

Keith Thompson

unread,
May 26, 2013, 2:40:06 PM5/26/13
to
That's not going to work if each word is evaluated independently of it
context. After "20 b", the stack is going to contain 20 and the *value*
of b; the "=" doesn't have a reference to the *variable* b to work with.
C resolves this by treating an object name as an lvalue, and converting
it to an rvalue (taking its stored value) depending on the context.

I have my own RPN calculator; it uses "b" to push the value of b on the
stack, and "b=" as a single word to assign the value on top of the stack
to b.

Another approach would be to use a special syntax to push the name of a
variable onto the stack rather than its value, for example letting "b"
push the current value of b and ".b" push the name of b. Then "=" would
require the top stack item to be a name, not a value.

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
0 new messages