orangeduck / BuildYourOwnLisp

Learn C and build your own programming language in under 1000 lines of code!
http://www.buildyourownlisp.com/
Other
2.9k stars 394 forks source link

Different Solution #135

Closed firezdog closed 5 years ago

firezdog commented 5 years ago

I was working through this and came up with a rather different solution -- I don't think the algorithm, if that's the right word to describe it, is quite the same? Any thoughts on this in terms of best practices? I think yours is definitely much nicer to read...

int evaluate(mpc_ast_t* t) {
    if (strstr(t->tag, "numeral") != 0) {
        return atoi(t->contents);
    } else {
        // seems like the loops is needed here when working your way in to terms on the right.  Perhaps the loop could be replaced with an if check.
        for (int i = 0; i < t->children_num; i++) {
            if (strcmp(t->children[i]->contents,"+") == 0) {
                return atoi(t->children[i+1]->contents) + evaluate(t->children[i+2]);
            } else if (strcmp(t->children[i]->contents, "-") == 0) {
                return atoi(t->children[i+1]->contents) - evaluate(t->children[i+2]);
            } else if (strcmp(t->children[i]->contents, "*") == 0) {
                return atoi(t->children[i+1]->contents) * evaluate(t->children[i+2]);
            } else if (strcmp(t->children[i]->contents, "/") == 0) {
                return atoi(t->children[i+1]->contents) / evaluate(t->children[i+2]);
            }
        }
    }
}
firezdog commented 5 years ago

Note -- just realized that the returns need to evaluate both expressions on the left and right side of the operator -- that change being made, this solution also seems to work, give or take a few edge cases like + 1 1 1 (which I don't consider to be correctly formed because I think '+' is a binary operator)

i.e.

...
return evaluate(t->children[i+1]) + evalute(t->children[i+2])
orangeduck commented 5 years ago

Yeah, the interpretation is up to you so I think this is a good a solution as any if it produces the behaviour you think is right 👍