tags:

views:

104

answers:

2

Hi I'm writing rpn calculator in C and I'd to compile rpn expression to byte-code. But I'm not sure what would be the data structure to represent them??? My stack data structure so far is

 struct stack_t{
        int type;
        union {  
              double val;
              char *str;
              /* probably some more */
             }u;
    };
+1  A: 

It actually depends a lot on the feature set you are going to support. For example, if your calculator supports integers (e.g., integer division), you probably would need int in your union.

Vlad
A: 

The advantage of RPN bytecode is that it doesn't need to be stored in a special structure. An array/vector/list will do. You need a stack to interpret it, but to store the program you should only convert each token to a bytecode instruction.

As for what types to put in your union, it really depends on the semantics of your calculator. Why do you want to be able to store strings? Do you plan on using strong typing?

Look into Forth, the canonical simple RPN language.

Potatoswatter
my guess is that strings may be needed if we'd like to represent variables
Vlad
calculator + variables = interpreter
Potatoswatter
The calculator so far supports real number and string data type and variables also. Now I'd to add function definition and need to compile the input rather than interpreting on the fly.
Nyan
@Nyan: Note that Forth is typically compiled directly to machine code, even on the fly. It's also extensible to allow alternate RPN or even non-RPN syntax. See how fast an implementation of you language in Forth is before you put too much effort into your own.
Potatoswatter