Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Small S-exp like arithmetic code interpreter in Java
package org.komamitsu.test;
import java.util.StringTokenizer;
public class ArithmeticCodeEvaluator
{
private static int eval(StringTokenizer tokenizer)
{
String first = tokenizer.nextToken();
if (first.equals("+")) {
return eval(tokenizer) + eval(tokenizer);
}
else if (first.equals("-")) {
return eval(tokenizer) - eval(tokenizer);
}
else if (first.equals("*")) {
return eval(tokenizer) * eval(tokenizer);
}
else if (first.equals("/")) {
return eval(tokenizer) / eval(tokenizer);
}
else if (first.equals("(")) {
int result = eval(tokenizer);
String closeParen = tokenizer.nextToken();
if (!closeParen.equals(")")) {
throw new IllegalStateException("Expected ')', but got: " + closeParen);
}
return result;
}
return Integer.valueOf(first);
}
public static void main(String[] args)
{
String s = "(/ (* (+ 2 3) (- 10 4)) (+ 3 (/ 28 4)))";
int result = eval(new StringTokenizer(s, "() "));
System.out.println("Result: " + result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment