Skip to content

Instantly share code, notes, and snippets.

@BRonen
Created August 16, 2025 16:56
Show Gist options
  • Save BRonen/e09be273c5df18272720d9a0e5207a8a to your computer and use it in GitHub Desktop.
Save BRonen/e09be273c5df18272720d9a0e5207a8a to your computer and use it in GitHub Desktop.
Reverse polish notation arithmetic interpreter in JQ
def tokens:
split(" ") | map(select(length > 0));
def isnum:
test("^-?([0-9]+(\\.[0-9]+)?)$");
def evaluate:
def eval($tokens):
if ($tokens | length) == 0 then
error("ending unexpected")
else
($tokens[0]) as $f |
if ($f | isnum) then
[($f | tonumber), ($tokens[1:])]
elif ($f | IN("+","-","*","/")) then
eval($tokens[1:]) as [$x, $r] |
eval($r) as [$y, $rest] |
(if $f == "+" then $x + $y
elif $f == "-" then $x - $y
elif $f == "*" then $x * $y
else
if $y == 0 then
error("division by zero")
else
$x / $y
end
end) as $val
| [$val, $rest]
else
error("todo: \($f)")
end
end;
( . | tokens ) as $tokens
| eval($tokens) as [$result, $rest]
| if ($rest | length) > 0
then error("result value: \($result)\nremaining tokens: \($rest)")
else $result
end;
evaluate
@BRonen
Copy link
Author

BRonen commented Aug 16, 2025

echo "+ 2 2" | jq -Rr -f polish.jq
# 4
echo "+ - 3 2 - 2 1" | jq -Rr -f polish.jq
# 2
echo "+ * 3 2 - 2 1" | jq -Rr -f polish.jq
# 7
echo "* 3 / 4 2" | jq -Rr -f polish.jq
# 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment