Skip to content

Instantly share code, notes, and snippets.

@jkhoeini
Created September 10, 2015 13:49
Show Gist options
  • Select an option

  • Save jkhoeini/b8a8ac8478741b24b9ad to your computer and use it in GitHub Desktop.

Select an option

Save jkhoeini/b8a8ac8478741b24b9ad to your computer and use it in GitHub Desktop.

Revisions

  1. jkhoeini created this gist Sep 10, 2015.
    42 changes: 42 additions & 0 deletions RPNcalc.d
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    // RPN calculator
    import std.algorithm, std.container.array,
    std.conv, std.stdio, std.meta;

    void main()
    {
    Array!int stack;

    void binop(string op)()
    {
    stack[$ - 2] = mixin("stack[$ - 2] " ~
    op ~ " stack[$ - 1]");
    stack.removeBack();
    writeln(stack[$ - 1]);
    }

    void process(in char[] token)
    {
    alias Ops = AliasSeq!("+", "-", "*", "/", "%");
    Lswitch:
    switch (token)
    {
    foreach (op; Ops)
    {
    case op:
    binop!op();
    break Lswitch;
    }

    case "=":
    writeln(stack[$ - 1]);
    stack.removeBack();
    break;

    default:
    stack.insertBack(token.to!int);
    break;
    }
    }

    stdin.byLine.map!splitter.joiner.each!process;
    }