条件表达式的评估

Evaluation of conditional expressions

本文关键字:评估 表达式 条件      更新时间:2023-09-26

我正在尝试编写一种递归算法来计算以下类型的表达式:operator variable和返回true/false的函数。

 [A] = [B] - [c]
 functionA(1,2) = functionB(3,4,5)
 functionA(functionC(a,b)) = functionB(3,4,5)

问题是我不知道如何开始和使用什么方法。我可以使用堆栈或任何东西。
我正在尝试在Javascript中执行此操作。

欢迎任何逻辑/想法。

也许您正在寻找这个,一个函数集合和一个基于堆栈的 RPN 样式命令迭代。

在输出中,您可以看到实际的命令和堆栈。

var $ = {
        '===': function (b) { return function (a) { return a === b; }; },
        '+': function (b) { return function (a) { return a + b; }; },
        '-': function (b) { return function (a) { return a - b; }; },
        '1/x': function (a) { return 1 / a; },
    },
    commands = [3, 2, '+', 9, 4, '-', '==='],
    result = commands.reduce(function (stack, command) {
        var temp;
        if ($[command]) {
            temp = $[command];
            while (typeof temp === 'function') {
                temp = temp(stack.pop());
            }
            stack.push(temp);
        } else {
            stack.push(command);
        }
        document.write('<pre>' + command + ': ' + JSON.stringify(stack, 0, 4) + '</pre>');
        return stack;
    }, [])[0];
document.write(result);