Created
August 16, 2025 16:56
-
-
Save BRonen/e09be273c5df18272720d9a0e5207a8a to your computer and use it in GitHub Desktop.
Reverse polish notation arithmetic interpreter in JQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
BRonen
commented
Aug 16, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment