Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers".
This led to a programming challenge:
Implement a reverse polish notation calculator in C without using arrays and pointers.
Description
You must implement a RPN calculator that
- operates on integers,
- supports addition (+),
- supports multiplication (*).
Your implementation
- must not use pointers or arrays
- you may use structs
- the input is read from stdin
- your lexer may use pointers and arrays (but it shouldn't be needed)
- when EOF is read then print the top of the stack
- the behavior can be as undefined as you want for malformed input
- should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it)
The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable
typedef enum { val, op, eof } TYPE; typedef enum { add, mul } OPERATION; typedef struct { TYPE type; union { int val; OPERATION op; } dat; } token; token next(); A solution using a stack with push() and pop() could look something like this:
token t; while ((t = next()).type != eof) { switch (t.type) { case val: push(t.dat.val); case op: switch (t.dat.op) { case add: int v1 = pop(); int v2 = pop(); push(v1+v2); case mult: int v1 = pop(); int v2 = pop(); push(v1*v2); } case eof: printf("Result: %d\n", pop()); } } Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments.
I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover.
namespace path {::tcl::mathop}, then you can do it directly without implementing anything: codegolf.stackexchange.com/a/106284/29325 \$\endgroup\$