3 ms·
If you don't mind a regex-heavy approach, here's a single-method version in Ruby that handles precedence correctly and maintains the ability to pass in operator
by gojomo 18y ago
If you don't mind a regex-heavy approach, here's a single-method version in Ruby that handles precedence correctly and maintains the ability to pass in operators:
def in_to_pre_fix(expr, opers=%w(*/ +-))
subex = "\\s*(?:(?:<([^>]+)>)|([\\w]+))\\s*"
while expr !~ /^<[^>]*>$/ and expr.sub!(/(?:^|\()([^)(]*)(?:\)|$)/) { | m |
opers.each { | oper |
while m.sub!(Regexp.new("#{subex}([#{Regexp.quote(oper)}])#{subex}"),
'<\3 \1\2 \4\5>'); end }
m.tr_s("() "," ").strip() }; end
expr.delete("<>")
end
(I'm new to Ruby, so it may not be idiomatic or preferred whitespace-style.)