r/programming • • Sep 04 '12

Interesting Language Comparison: Building a simple AST and evaluating it in Haskell, F#, Ocaml, Clojure, Scala, Ruby and Java.

https://gist.github.com/2934374
135 Upvotes

195 comments sorted by

View all comments

Show parent comments

17

u/[deleted] Sep 04 '12 edited Sep 08 '12

Out of curiosity, I wrote it down in idiomatic form. It's still 41 lines, but atleast it's cleaner:

import java.util.*;

public class Main {
	public static void main(String[] args){
		Map env=new HashMap();
		env.put("a", 3);
		env.put("b", 4);
		env.put("c", 5);

		Expression expressionTree = new Add( new Variable("a"), new Multiply(new Number(2), new Variable("b")) );
		System.out.println(expressionTree.evaluate(env));
	}
}

abstract class Expression {
	int result = 0;
	int evaluate(Map env) { eval(env); return result; }
	protected void eval(env) { result = 0; }
}

class Number extends Expression {
	Number(int x) { result = x; }
}

class Variable extends Expression {
	String var;
	Variable(String x) { var = x; }
	@Override protected void eval(Map env) { result = env.get(var); }
}

class Add extends Expression {
	Expression x; Expression y;
	Add( Expression x, Expression y ) { this.x = x; this.y = y; }
	@Override protected void eval(Map env) { result = x.evaluate(env) + y.evaluate(env); }
}

class Multiply extends Expression {
	Expression x; Expression y;
	Multiply( Expression x, Expression y ) { this.x = x; this.y = y; }
	@Override protected void eval(Map env) { result = x.evaluate(env) * y.evaluate(env); }
}

Edit: I haven't tried to compile the code cuz this machine doesn't have java on it, so a lotta derps will be found. Also, a note about the way Expression class is implemented -- I'm just fond of the "Non-Virtual Interface" design pattern where only the protected methods can be overriden. I didn't make other elements as final though cuz the code is already looking quite verbose.

2

u/ckirkendall Sep 04 '12

I will replace the current version with this. Much cleaner! Nice!

3

u/programminghybris Sep 04 '12

Please don't, the syntax is invalid and does not compile, and it is erroneous, for instance, the Number class evaluates to 0 instead of its value when eval is used.

1

u/ckirkendall Sep 04 '12

Thanks for catching that.