r/dailyprogrammer • • Sep 15 '17
[2017-09-15] Challenge #331 [Hard] Interactive Interpreter
[deleted] — view deleted post
72
Upvotes
r/dailyprogrammer • • Sep 15 '17
[deleted] — view deleted post
2
u/myvaria Sep 17 '17
My Goal for this implementation is to try and keep it minimalistic and simple, i decided to opt for a single class design instead of a multi class oop huge implementation, the only downside of this is that i can not provide very detailed error information if the input expression is malformed or wrong in some way.
Please note i have dyslexia so spelling is bad sorry.
The implementation was done in C#
Gist Link
7
u/quantik64 Sep 15 '17 edited Sep 19 '17
This is really funny that this was this weeks challenge because I actually did this after the
Easychallenge earlier this week. I just had to add parentheses and variable capabilities. No bonuses (yet) but I'll try to add them.EDIT: Added much improved version that made it more theoretical sound (like replacing the 'searching' for equivalences with actually parsing/tokenizing everything) and include function capabilities. It needs a couple of tweaks but I'm pretty satisfied with it.
C++11
10
u/skeeto -9 8 Sep 15 '17
C using the shunting-yard algorithm. It handles errors and rejects most invalid input, though it doesn't explain the reason. Divide by zero is not an error, per IEEE 754.
1
u/Hypersigils Sep 16 '17
Java, without bonuses.
2
u/cheers- Sep 15 '17 edited Sep 15 '17
Javascript (Node)
A Pratt Parser that uses syntax directed translation.
usage
Intepreter.js
parser.js
symbols.js
lexer.js:
https://pastebin.com/7raJdRZH (I didnt include here to not make this post too long)
2
u/__dict__ Sep 20 '17
Ruby. Builds an AST then evaluates it.
2
u/TKraus Oct 04 '17
This is my Java solution. Its probably wildly inefficient but nonetheless lmk what you think.
2
u/snhmib Oct 13 '17 edited Oct 13 '17
It's been a while since a programmed anything, comments and tips are welcome.
I programmed this in C, features include:
minimal error checking
include <ctype.h>
include <err.h>
include <stdio.h>
include <stdlib.h>
include <string.h>
include <math.h>
define NAME_MAX 1024
// operators are in order of precedence struct token { enum {VAR, CONST, ASSIGN, ADD, SUB, MUL, DIV, EXP, LBRACK, RBRACK, EOL, END} what; union { char name[NAME_MAX]; double value; }; };
int isop(int what) { return ASSIGN <= what && what < LBRACK; }
/********************************************************************************
define SYMTAB_SIZE 2053
struct symtab { char name[NAME_MAX]; //stupid trick: if name == "", this entry is empty double value; struct symtab *next; } symtab[SYMTAB_SIZE];
/* random hash function from the internet
int bucket_is_empty(const struct symtab *t) { return t->name[0] == '\0'; }
void enter(const char *name, double value) { int h = hash(name) % SYMTAB_SIZE;
}
double lookup(const char name) { unsigned long h = hash(name) % SYMTAB_SIZE; struct symtab b = symtab + h; if (bucket_is_empty(b)) { errx(1, "variable <%s> doesn't exist\n", name); } while (b && strcmp(b->name, name)) b = b->next; if (!b) errx(1, "variable <%s> doesn't exist\n", name); return b->value; } /******************************************************************************
void collect_name(char *name) { int c, i = 0;
}
void print_token(const struct token t) { switch (t->what) { case END: printf("end-of-file\n"); break; case EOL: printf("end-of-line\n"); break; case VAR: printf("variable: <%s>\n", t->name); break; case CONST: printf("constant: <%lf>\n", t->value); break; default: printf("operator: <%c>\n", "..=+-/"[t->what]); break; } }
/* get next token from stdin
allocate memory for name (leaky but meh) */ struct token lex() { struct token token = { 0 }; static enum {OPERATOR, OPERAND} expect = OPERAND; int c = getchar();
/* skip whitespace except newlines */ while (isspace(c) && c != '\n') c = getchar();
if (c == EOF) { token.what = END; expect = OPERAND; } else if (c == '\n') { token.what = EOL; expect = OPERAND; } else if (isdigit(c) || (expect == OPERAND && '-' == c)) { // negative numbers are the entire reason for 'expect' variable token.what = CONST; ungetc(c, stdin); token.value = collect_num(); expect = OPERATOR; } else if (isalpha(c)) { token.what = VAR; ungetc(c, stdin); collect_name(token.name); expect = OPERATOR; } else { switch (c) { case '=': token.what = ASSIGN; break; case '+': token.what = ADD; break; case '-': token.what = SUB; break; case '*': token.what = MUL; break; case '/': token.what = DIV; break; case '': token.what = EXP; break; case '(': token.what = LBRACK; break; case ')': token.what = RBRACK; break; default: errx(1, "bad input: %c.\n", c); break; } expect = OPERAND; }
return token; }
/********************************************************************************
define STK_MAX 256
struct token valuestack[STK_MAX]; struct token opstack[STK_MAX]; int value_idx = 0, op_idx = 0;
void pushvalue(struct token t) { if (value_idx + 1 == STK_MAX) errx(1, "value stack is full\n");
}
void pushop(struct token t) { if (op_idx + 1 == STK_MAX) errx(1, "operand stack is full\n"); opstack[op_idx++] = t; }
int popop(void) { if (op_idx-- == 0) errx(1, "operand stack is empty\n"); return opstack[op_idx].what; }
int peekop(void) { if (op_idx == 0) return 0; else return opstack[op_idx-1].what; }
double popval(void) { if (value_idx-- == 0) errx(1, "value stack is empty\n"); struct token *this = valuestack + value_idx; if (this->what == VAR) return lookup(this->name); else return this->value; }
char * poplval(void) { if (value_idx-- == 0) errx(1, "value stack is empty\n"); struct token *this = valuestack + value_idx; if (this->what != VAR) errx(1, "value is not assignable\n"); return this->name; }
void exec(int op) { double l,r; struct token result; result.what = CONST; switch (op) { case ASSIGN: result.value = popval(); enter(poplval(), result.value); break; case ADD: result.value = popval() + popval(); break; case SUB: r = popval(); l = popval(); result.value = l - r; break; case MUL: result.value = popval() * popval(); break; case DIV: r = popval(); l = popval(); result.value = l / r; break; case EXP: r = popval(); l = popval(); result.value = pow(l,r); break; } pushvalue(result); }
int main(int argc, char *argv) { struct token token; for (token = lex(); token.what != END; token = lex()) { if (token.what == EOL) { while (peekop()) exec(popop()); printf("%lf\n", popval()); if (value_idx != 0 || op_idx != 0) { warn("bad expression: end of line but stack still full\n"); value_idx = 0; op_idx = 0; } } else if (token.what == CONST || token.what == VAR) { pushvalue(token); } else if (token.what == LBRACK) { pushop(token); } else if (token.what == RBRACK) { int op; while (LBRACK != (op = popop())) exec(op); } else { / token must be operator */ while (isop(peekop()) && peekop() > token.what) { exec(popop()); } pushop(token); } } return 0; }
1
u/FrankRuben27 0 1 Sep 17 '17 edited Sep 17 '17
Nice challenge. Solution in Bigloo Scheme, which - using its integrated LALR parser - is close to cheating (EDIT: sorry - read the advise to not use built-in evaluators just now, it might very well apply here). Supporting the bonus in return:
1
u/TheMaster420 Sep 18 '17 edited Sep 18 '17
(java)I was too lazy to do decent error checking, I did do the bonus exercise. Maybe as next exercise we can add conditional statements, labels and gotos? Maybe I'll implement a better version later with shunting yard.
EDIT: implemented conditonal operations so fac(x)=?(x)(xfac(x-1))(1) works. Some bugfixes ( apparently 1-1-1 didn't work in my version) known bugs:the name of recursive functions can't contain one of the variable names of that function fac(x)=?(x)(xfac(x-1))(1), scientific notation values aren't interpreted correctly EDIT2: fixed scientific notation, don't use capital E for functions/variables
1
u/Ollowayne Sep 18 '17 edited Sep 19 '17
Concise solution in Prolog. I don't have much Prolog experience, but this just looked to fun of a problem to not use it.
EDIT: Now includes the first bonus and the second one partially (only evaluation errors).
To run on the challenge input (non interactive):
1
u/cosmez Sep 19 '17
C# First Time Writing a Lexer/Parser by hand. it looks like shit, but it mostly works.
https://gist.github.com/cosmez/30aeea7951a0c3a89a33c0b525bc7338
1
u/_tpr_ Sep 20 '17 edited Sep 20 '17
This took me a pretty long time. I haven't learned enough about Haskell to make things easy. So instead of being interactive, it takes a script and prints the final value. I also didn't implement parentheses or order of operation. I chose to use the J order of operation -- right to left.
Haskell
1
u/zookeeper_zeke Sep 22 '17 edited Sep 22 '17
Here's my solution in C. It uses the Shunting-yard algorithm likes others in the thread do. It does rudimentary error checking catching things like:
https://gist.github.com/anonymous/58bd8513410fca07d375a1cc5e66be30
1
u/NITROGENarcosis Oct 03 '17
Python 3 no bonus
just getting back into programming so any critiques/suggestions are welcomed
-5
u/imaconor Sep 15 '17 edited Sep 15 '17
0
u/[deleted] Sep 15 '17
[deleted] — view deleted comment