summaryrefslogtreecommitdiff
path: root/rpn.c
diff options
context:
space:
mode:
authorrodri <rgl@antares-labs.eu>2020-02-22 09:56:09 +0000
committerrodri <rgl@antares-labs.eu>2020-02-22 09:56:09 +0000
commita39951d8f69209cfea2b7051832b851914e662ef (patch)
treee4cd1c32e5d6f531b523f6fda558cc3a5f603547 /rpn.c
downloadbrokentoys-a39951d8f69209cfea2b7051832b851914e662ef.tar.gz
brokentoys-a39951d8f69209cfea2b7051832b851914e662ef.tar.bz2
brokentoys-a39951d8f69209cfea2b7051832b851914e662ef.zip
now version controlled.
Diffstat (limited to 'rpn.c')
-rw-r--r--rpn.c51
1 files changed, 51 insertions, 0 deletions
diff --git a/rpn.c b/rpn.c
new file mode 100644
index 0000000..010afde
--- /dev/null
+++ b/rpn.c
@@ -0,0 +1,51 @@
+#include <u.h>
+#include <libc.h>
+#include <ctype.h>
+#include <bio.h>
+
+int stk[256], sp;
+Biobuf *bin;
+
+void
+push(int n)
+{
+ if(sp >= sizeof stk)
+ sp = sizeof(stk)-1;
+ fprint(2, "push [%d] %d\n", sp, n);
+ stk[sp++] = n;
+}
+
+int
+pop(void)
+{
+ if(sp <= 0)
+ sp = 1;
+ fprint(2, "pop [%d] %d\n", sp-1, stk[sp-1]);
+ return stk[--sp];
+}
+
+void
+main()
+{
+ int x;
+ char c;
+
+ bin = Bfdopen(0, OREAD);
+ if(bin == nil)
+ sysfatal("Bfdopen: %r");
+ while((c = Bgetc(bin)) != Beof){
+ x = 0;
+ switch(c){
+ case '+': x = pop() + pop(); break;
+ case '*': x = pop() * pop(); break;
+ default:
+ while(isdigit(c)){
+ x = x*10 + c-'0';
+ c = Bgetc(bin);
+ }
+ }
+ push(x);
+ }
+ print("%d\n", pop());
+ exits(nil);
+}