3 ms·
I can’t bring myself to write blog posts, but here’s a single-precedence-level infix-to-postfix notation transformer in sed written as part of a solution for la
by mananaysiempre 5y ago
I can’t bring myself to write blog posts, but here’s a single-precedence-level infix-to-postfix notation transformer in sed written as part of a solution for last year’s Advent of Code 18a (https://adventofcode.com/2020/day/18 https://adventofcode.com/2020/day/18):
#!/bin/sh -eu
set -o pipefail
sed -E \
-e 's/([+*])\s*([0-9]+)/ \2 \1 /g' \
-e ':parens' \
-e 's/([+*])\s*(\([^()]+\))/ \2 \1 /g' \
-e 's/\(([^()]+)\)/ \1 /g' \
-e '/\(/bparens' \
-e 's/\s+/ /g' -e 's/^ //' -e 's/ $//' \
-e '$a\' -e '[+ z1<r]sr z1<r p' | \
dc
(I’m very, very sorry for fuelling your addiction.)
UPD: The original version claimed this was a precedence parser. It isn’t, it just does parentheses :(
- jolmg 5y agoMaybe I'm doing something wrong, but passing it "3 * 4 + 5 * 6" gives me 102 instead of 42.
- mananaysiempre 5y agoYou are correct; I seemed to remember there was a catch but was too lazy to check, sorry. This isn’t a precedence parser, that was 18b, while this one solves 18a, which was just to resolve parentheses correctly and disregard precedence. (Original comment fixed.)