Skip to content

Instantly share code, notes, and snippets.

@brendanw
Created August 2, 2015 19:15
Show Gist options
  • Save brendanw/39ffa11895aeadaea2ff to your computer and use it in GitHub Desktop.
Save brendanw/39ffa11895aeadaea2ff to your computer and use it in GitHub Desktop.
package com.simplelisp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SimpleLisp {
//(+ 3 (+ 3 2) (+ 4 5))
// (+
private static HashMap<String, Integer> assignmentMap = new HashMap<>();
public static void main(String[] args) {
String inputA = "(+ 3 (* 2 3) (+ 2 4))"; //(function arg1 arg2); this is one expression
System.out.println(inputA + " -> " + eval(inputA));
String inputB = "(let x 5)";
System.out.println(inputB + " -> " + eval(inputB));
String inputC = "(+ x 5)";
System.out.println(inputC + " -> "+eval(inputC));
}
private static String eval(String expression) {
/** we are going to parse the function type out */
StringBuilder sb = new StringBuilder("");
int pointer = 0;
while (expression.charAt(pointer) != ' ') {
if (expression.charAt(pointer) != '(') {
sb.append(expression.charAt(pointer));
}
pointer++;
}
String function = sb.toString();
sb.delete(0, sb.length());
pointer++; //we are now past the space and on the first expression/value
/** we are going to parse our list of expressions */
List<String> arguments = new ArrayList<>();
while(pointer <= (expression.length() - 1)) {
if(expression.charAt(pointer) != '(') {
while(pointer <= (expression.length() - 1) && expression.charAt(pointer) != ' '
&& expression.charAt(pointer) != ')') {
sb.append(expression.charAt(pointer));
pointer++;
}
String argument = sb.toString();
if(assignmentMap.containsKey(argument)) {
arguments.add(assignmentMap.get(argument).toString());
} else {
arguments.add(argument);
}
sb.delete(0, sb.length());
} else {
int parens = 1;
sb.append('(');
pointer++;
while(parens != 0) {
if(expression.charAt(pointer) == '(') parens++;
if(expression.charAt(pointer) == ')') parens--;
sb.append(expression.charAt(pointer));
pointer++;
}
arguments.add(eval(sb.toString()));
sb.delete(0, sb.length());
}
pointer++;
}
/** operate the function over the list of expressions */
switch(function) {
case "+": {
Integer returnVal = 0;
for(String arg : arguments) {
returnVal += Integer.parseInt(arg);
}
return returnVal.toString();
}
case "-": {
Integer returnVal = 0;
for(String arg : arguments) {
returnVal -= Integer.parseInt(arg);
}
return returnVal.toString();
}
case "*": {
Integer returnVal = 1;
for(String arg : arguments) {
returnVal *= Integer.parseInt(arg);
}
return returnVal.toString();
}
case "let": {
Integer val = Integer.parseInt(arguments.get(1));
assignmentMap.put(arguments.get(0), val);
return arguments.get(0)+"="+val;
}
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment