Parsing/RPN calculator algorithm: Difference between revisions

added ceylon
m (→‎{{header|Sidef}}: minor code simplifications)
(added ceylon)
Line 726:
 
Result is 3.0001220703125
</pre>
 
=={{header|Ceylon}}==
<lang>shared void run() {
value ops = map {
"+" -> plus<Float>,
"*" -> times<Float>,
"-" -> ((Float a, Float b) => a - b),
"/" -> ((Float a, Float b) => a / b),
"^" -> ((Float a, Float b) => a ^ b)
};
void printTableRow(String|Float token, String description, {Float*} stack) {
print("``token.string.padTrailing(8)````description.padTrailing(30)````stack``");
}
function calculate(String input) {
value stack = ArrayList<Float>();
value tokens = input.split().map((String element)
=> if(ops.keys.contains(element)) then element else parseFloat(element));
print("Token Operation Stack");
for(token in tokens.coalesced) {
if(is Float token) {
stack.push(token);
printTableRow(token, "push", stack);
} else if(exists op = ops[token], exists first = stack.pop(), exists second = stack.pop()) {
value result = op(second, first);
stack.push(result);
printTableRow(token, "perform ``token`` on ``formatFloat(second, 1, 1)`` and ``formatFloat(first, 1, 1)``", stack);
} else {
throw Exception("bad syntax");
}
}
return stack.pop();
}
print(calculate("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
}</lang>
{{out}}
<pre>Token Operation Stack
3.0 push { 3.0 }
4.0 push { 3.0, 4.0 }
2.0 push { 3.0, 4.0, 2.0 }
* perform * on 4.0 and 2.0 { 3.0, 8.0 }
1.0 push { 3.0, 8.0, 1.0 }
5.0 push { 3.0, 8.0, 1.0, 5.0 }
- perform - on 1.0 and 5.0 { 3.0, 8.0, -4.0 }
2.0 push { 3.0, 8.0, -4.0, 2.0 }
3.0 push { 3.0, 8.0, -4.0, 2.0, 3.0 }
^ perform ^ on 2.0 and 3.0 { 3.0, 8.0, -4.0, 8.0 }
^ perform ^ on -4.0 and 8.0 { 3.0, 8.0, 65536.0 }
/ perform / on 8.0 and 65536.0 { 3.0, 1.220703125E-4 }
+ perform + on 3.0 and 0.0 { 3.0001220703125 }
3.0001220703125
</pre>
 
Anonymous user