如何递归解析括号内的子字符串

时间:2019-04-22 23:19:26

标签: java parsing lisp interpreter

我正在用Java编写LISP解释器,并且试图创建一个函数,该函数可以将一组括号内的所有参数递归地动态评估为单个值。它需要解决需要评估的输入参数的任何组合。例如,+ 2 3意味着不需要求解参数,+ (+ 1 2) (+ 1 2)意味着两个参数都需要求解,+ 1 (+ 1 2)意味着仅第二个参数需要求解,而+ (+ 1 2) 1意味着仅第一个参数需要求解。在这种情况下,我假设所有可以执行的操作只有2个参数(+,-,*,/等)

我已经包含了已经有效的代码片段。如果两个参数都需要求解,或者两个参数都不需要求解,则我的函数可以解析输入。我的问题是我无法找到一种方法来检查是否只需要解决一个参数。注意:我故意将结果作为字符串返回。

public String test(String input) { //input comes in without outter-most parentheses

        String param1, param2;
        if (input.indexOf('(') != -1) { //'(' exists somewhere in the string

            int param1Start = input.indexOf('(');
            int iter = param1Start + 1;
            int c = 1;
            while (c != 0) { //loop through the string until the matching close parentheses is found
                if (input.charAt(iter) == '(')
                    c++;
                if (input.charAt(iter) == ')')
                    c--;
                iter++;
            }
            String subs1 = input.substring(param1Start + 1, iter - 1);

            param1 = test(subs1); //further evaluate the first parameter

            int param2Start = iter + 1;
            iter = param2Start + 1;
            c = 1;
            while (c != 0) { //loop through the string until the matching close parentheses is found
                if (input.charAt(iter) == '(')
                    c++;
                if (input.charAt(iter) == ')')
                    c--;
                iter++;
            }
            String subs2 = input.substring(param2Start + 1, iter - 1);
            param2 = test(subs2); //further evaluate the second parameter
        } else { //no parentheses left in string, solving time
            String[] splitter = input.split(" ", 3);

            return Integer.toString(Integer.parseInt(splitter[1]) + Integer.parseInt(splitter[2]));
        }
        return Integer.toString(Integer.parseInt(param1) + Integer.parseInt(param2));


    }

有人能找到一种方法来检查是否只需要评估一个参数吗?还是发布更好的Java解决方案?

0 个答案:

没有答案