Anonymous user
Parsing/RPN calculator algorithm: Difference between revisions
Updated to work with Nim 1.4: added missing parameter type and done other changes.
Alextretyak (talk | contribs) m (→{{header|11l}}) |
(Updated to work with Nim 1.4: added missing parameter type and done other changes.) |
||
Line 3,198:
type Stack = seq[float]
proc opPow(s: var Stack) =
Line 3,227 ⟶ 3,224:
s.add a - b
proc opNum(s: var Stack
s.add num
let ops = toTable({"^": opPow,
Line 3,241 ⟶ 3,239:
result = inp.strip.split
proc rpnCalc(tokens: seq[string]):
var s: Stack
result = @[@["TOKEN","ACTION","STACK"]]
for token in tokens:
Line 3,252 ⟶ 3,250:
action = "Push num onto top of stack"
s.opNum token.parseFloat
result.add(@[token, action, s
let rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
Line 3,261 ⟶ 3,259:
for i in 0 .. rp[0].high:
for x in rp:
maxColWidths[i] = max(maxColWidths[i], x[i].len + 3)
for x in rp:
for i, y in x:
stdout.write y.
echo ""</lang>
{{out}}
<pre>For RPN expression: 3 4 2 * 1 5 - 2 3 ^ ^ / +
TOKEN ACTION STACK
3 Push num onto top of stack 3.0
4 Push num onto top of stack 3.0 4.0
2 Push num onto top of stack 3.0 4.0 2.0
* Apply op to top of stack 3.0 8.0
1 Push num onto top of stack 3.0 8.0 1.0
5 Push num onto top of stack 3.0 8.0 1.0 5.0
- Apply op to top of stack 3.0 8.0 -4.0
2 Push num onto top of stack 3.0 8.0 -4.0 2.0
3 Push num onto top of stack 3.0 8.0 -4.0 2.0 3.0
^ Apply op to top of stack 3.0 8.0 -4.0 8.0
^ Apply op to top of stack 3.0 8.0 65536.0
/ Apply op to top of stack 3.0 0.0001220703125
+ Apply op to top of stack 3.0001220703125 </pre>
=={{header|Objeck}}==
|