Parsing/RPN calculator algorithm: Difference between revisions

(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
Line 2,683:
+: 3.0001220703125
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq, and with jackson-jq and fq.'''
<syntaxhighlight lang=jq>
# Input: an array representing a stack, with .[-1] being its top.
# Output: the updated array after applying `op`
def rpn(op):
def two: .[-2:];
def update($x): (.[:-2] + [$x]);
if length<=1 then .
elif op == "+" then update(two | add)
elif op == "/" then update(two | (.[0] / .[1]))
elif op == "*" then update(two | (.[0] * .[1]))
elif op == "/" then update(two | (.[0] / .[1]))
elif op == "-" then update(two | (.[0] - .[1]))
elif op == "^" then update(two | (pow(.[0]; .[1])))
else ("ignoring unrecognized op \(op)" | debug) as $debug | .
end;
 
def eval:
foreach .[] as $item ([];
if ($item | type) == "number" then . + [$item]
else rpn($item)
end;
"\($item) => \(.)" ) ;
 
"3 4 2 * 1 5 - 2 3 ^ ^ / +"
| split(" ") | map( (try tonumber) // .)
| eval
</syntaxhighlight>
''Invocation:'' jq -nr -f rpn.jq
{{output}}
<pre>
3 => [3]
4 => [3,4]
2 => [3,4,2]
* => [3,8]
1 => [3,8,1]
5 => [3,8,1,5]
- => [3,8,-4]
2 => [3,8,-4,2]
3 => [3,8,-4,2,3]
^ => [3,8,-4,8]
^ => [3,8,65536]
/ => [3,0.0001220703125]
+ => [3.0001220703125]
</pre>
 
 
=={{header|Julia}}==
2,460

edits