Created
June 9, 2019 14:38
-
-
Save komamitsu/83ea0044fbef06632919277590887654 to your computer and use it in GitHub Desktop.
Small S-exp like arithmetic code interpreter in Java
This file contains hidden or 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
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