package java_programs;
import java.util.*;
import java.util.function.BinaryOperator;

/**
 *
 * @author derricklin
 */
public class RPN_EVAL {
    public static Double rpn_eval(ArrayList<Object> tokens) {
        Map<String, BinaryOperator<Double>> op = new HashMap<>();
        op.put("+", (a, b) -> a + b);
        op.put("-", (a, b) -> b - a);  // Note the order for correct subtraction
        op.put("*", (a, b) -> a * b);
        op.put("/", (a, b) -> b / a);  // Note the order for correct division

        Stack<Double> stack = new Stack<>();

        for (Object token : tokens) {
            if (token instanceof Double) {
                stack.push((Double) token);
            } else {
                String operator = (String) token;
                Double a = stack.pop();
                Double b = stack.pop();
                Double result = op.get(operator).apply(a, b);
                stack.push(result);
            }
        }

        return stack.pop();
    }
}