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).

1  
// sequence can contain operators (+, -, *, /), Doubles or string-encoded doubles
2  
srecord CalcRPN(L sequence) is Steppable {
3  
  int i;
4  
  new DoubleList stack;
5  
  
6  
  run { stepAll(this); }
7  
  
8  
  bool done() { ret i >= l(sequence); }
9  
  
10  
  public bool step() {
11  
    if (done()) false;
12  
    O o = sequence.get(i++);
13  
    if (eq(o, "*")) perform((a, b) -> a * b);
14  
    else if (eq(o, "/")) perform((a, b) -> doubleRatio(a, b));
15  
    else if (eq(o, "+")) perform((a, b) -> a + b);
16  
    else if (eq(o, "-")) perform((a, b) -> a - b);
17  
    else if (eq(o, "u-")) perform(a -> -a);
18  
    else if (o cast S)
19  
      handleUnknownString(o);
20  
    else
21  
      stack.add(toDouble(o));
22  
    true;
23  
  }
24  
25  
  void handleUnknownString(S s) {
26  
    stack.add(toDouble(trim(s)));
27  
  }
28  
    
29  
  void perform(IF2<Double> f) {
30  
    var arg2 = popLast(stack);
31  
    var arg1 = popLast(stack);
32  
    stack.add(f.get(arg1, arg2));
33  
  }
34  
  
35  
  void perform(IF1<Double> f) {
36  
    stack.add(f.get(popLast(stack)));
37  
  }
38  
  
39  
  double get() {
40  
    run();
41  
    assertEquals(1, l(stack));
42  
    ret last(stack);
43  
  }
44  
}

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: 119 / 249
Version history: 10 change(s)
Referenced in: [show references]