Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

44
LINES

< > BotCompany Repo | #1032662 // CalcRPN - calculate reverse polish notation

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (5318L/30K).

// sequence can contain operators (+, -, *, /), Doubles or string-encoded doubles
srecord CalcRPN(L sequence) is Steppable {
  int i;
  new DoubleList stack;
  
  run { stepAll(this); }
  
  bool done() { ret i >= l(sequence); }
  
  public bool step() {
    if (done()) false;
    O o = sequence.get(i++);
    if (eq(o, "*")) perform((a, b) -> a * b);
    else if (eq(o, "/")) perform((a, b) -> doubleRatio(a, b));
    else if (eq(o, "+")) perform((a, b) -> a + b);
    else if (eq(o, "-")) perform((a, b) -> a - b);
    else if (eq(o, "u-")) perform(a -> -a);
    else if (o cast S)
      handleUnknownString(o);
    else
      stack.add(toDouble(o));
    true;
  }

  void handleUnknownString(S s) {
    stack.add(toDouble(trim(s)));
  }
    
  void perform(IF2<Double> f) {
    var arg2 = popLast(stack);
    var arg1 = popLast(stack);
    stack.add(f.get(arg1, arg2));
  }
  
  void perform(IF1<Double> f) {
    stack.add(f.get(popLast(stack)));
  }
  
  double get() {
    run();
    assertEquals(1, l(stack));
    ret last(stack);
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1032662
Snippet name: CalcRPN - calculate reverse polish notation
Eternal ID of this version: #1032662/11
Text MD5: 31a1f3dcb1533e50eec3b0a7c56bc552
Transpilation MD5: 6a7f98cb8ba0ad4c001c0ba19215e329
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-10-02 00:58:25
Source code size: 1086 bytes / 44 lines
Pitched / IR pitched: No / No
Views / Downloads: 113 / 240
Version history: 10 change(s)
Referenced in: [show references]