Hello, inspired by the "Tiny RPN calculator" example seen on the dlang homepage, I wanted to create my own version.

I'd appreciate your opinions regarding style, mistakes/code smell/bad practice. Thank you.

    import std.array;
    import std.conv;
    import std.stdio;

    void main(string[] args)
    {
        if (args.length == 1)
        {
writeln("usage examples:\n\t", args[0], " 5 3 + 2 *\n\t", args[0],
                    " 12.1 11 /");
            return;
        }

        immutable string valid_ops = "+-*/";
        string spaced_args = args[1 .. $].join(" ");

// this is done to correctly handle "messy" inputs such as "5 3 2*+"
        foreach (o; valid_ops)
        {
            spaced_args = spaced_args.replace(o, " " ~ o ~ " ");
        }

        real[] stack;

        foreach (op; spaced_args.split)
        {
    LabeledSwitch:
            switch (op) // operator or operand?
            {
                static foreach (o; valid_ops)
                {
                case [o]:
                    stack = stack[0 .. $ - 2] ~
mixin("stack[$ - 2]" ~ o ~ "stack[$ - 1]");
                    break LabeledSwitch;
                }
            default:
                // assume it's an operand, a real number
                stack ~= to!real(op);
                break;
            }
        }

        writeln(stack);
    }

Reply via email to