Created
October 9, 2017 21:47
-
-
Save lukehoban/00cb5522e64cdaa6b3a3fcdd656edc76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IHashtable | |
{ | |
double lookup(string i); | |
void set(string i, double d); | |
} | |
class Hashtable() | |
{ | |
var o = {}; | |
public double lookup(string i) | |
{ | |
return this.o[i]; | |
} | |
public void set(string i, double d) | |
{ | |
this.o[i] = d; | |
} | |
} | |
interface IExpression { | |
double evaluate(IHashtable vars); | |
} | |
class Constant(double value) : IExpression { | |
public double evaluate(IHashtable vars) { | |
return value; | |
} | |
} | |
class VariableReference(string name) : IExpression { | |
public double evaluate(IHashtable vars) { | |
var value = vars.lookup(name); | |
return value; | |
} | |
} | |
class Operation(IExpression left, string op, IExpression right) : IExpression { | |
public double evaluate(IHashtable vars) { | |
double x = this.left.evaluate(vars); | |
double y = this.right.evaluate(vars); | |
switch (this.op) { | |
case '+': return x + y; | |
case '-': return x - y; | |
case '*': return x * y; | |
case '/': return x / y; | |
} | |
} | |
} | |
IExpression e = new Operation(new VariableReference("x"),'+',new Constant(3)); | |
function f() { | |
IExpression e = new Operation( new VariableReference("x"), | |
'*', new Operation( new VariableReference("y"), '+', new Constant(2) )); | |
IHashtable vars = new Hashtable(); | |
vars.set("x", 3); | |
vars.set("y", 5); | |
e.evaluate(vars); // Outputs "21" | |
vars.set("x", 1.5); | |
vars.set("y", 9); | |
return e.evaluate(vars); // Outputs "16.5" | |
} | |
f(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment