Re:A Handwritten Math Parser in 100 lines of Python
by wryun on Thursday September 17, 2020 @08:10AM
(#24503607)
Slightly more amusingly, but non-equivalently:
Does support order of operations, in spite of appearance. Extending to support parentheses is left as an exercise for the reader :)
[ Parent
| on HN ]
Re:A Handwritten Math Parser in 100 lines of Python
by ogogmad on Thursday September 17, 2020 @08:55AM
(#24504000)
It's pretty horrible, but this adds support for parentheses inside the `full_eval` function:
from itertools import takewhile, dropwhile
def split_paren(expr):
left = ''.join(takewhile(lambda c: c != '(', expr))
right = ''.join(takewhile(lambda c: c != ')', expr[::-1]))[::-1]
inside = ''.join(dropwhile(lambda c: c != ')', ''.join(dropwhile(lambda c: c != '(', expr))[::-1]))[::-1][1:-1]
return left, inside, right
def full_eval(expr):
if '(' in expr:
left, inside, right = split_paren(expr)
return full_eval(left + str(full_eval(inside)) + right)
else:
return calc(expr)
Re:A Handwritten Math Parser in 100 lines of Python
by wryun on Thursday September 17, 2020 @09:04AM
(#24504085)
Neat! Well, sort of. Sometimes, certain things would look nicer not written in Python...
Re:A Handwritten Math Parser in 100 lines of Python
by tgb on Thursday September 17, 2020 @09:38AM
(#24504435)
This is pretty clever. There's a video by Jonathan Blow, creator of Braid and currently making a programming language called Jai, that talks about parsing expressions with order of operations. He gives an simple approach that apparently was discovered recently (though he didn't remember the paper name) that does this in a single pass and hardly any more complicated than what you wrote. You can see it here [1]. He also trashes on using yacc/bison before that and on most academic parsing theory.
Re:A Handwritten Math Parser in 100 lines of Python
by westurner on Thursday September 17, 2020 @10:13AM
(#24504857)
Reverse Polish notation (RPN) > Converting from infix notation
https://en.wikipedia.org/wiki/Reverse_Polish_notation#Conver... > Shunting-yard algorithm
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
Infix notation supports parentheses.
Infix notation: 3 + 4 × (2 − 1)
RPN: 3 4 2 1 − × +
Re:A Handwritten Math Parser in 100 lines of Python
by mucinoab on Thursday September 17, 2020 @11:43AM
(#24506025)
I would like to know the name of that paper if anyone knows.
Re:A Handwritten Math Parser in 100 lines of Python
by lioeters on Friday September 18, 2020 @01:10AM
(#24513210)
I believe he was talking about Pratt parsing in the video.
Top Down Operator Precedence - Vaughan R. Pratt - https://tdop.github.io/
What he called "priority" is called "binding power" in the paper.
Re:A Handwritten Math Parser in 100 lines of Python
by Leszek on Friday September 18, 2020 @04:50AM
(#24514474)
I like Jonathan Blow and all, but he should be careful with trashing academic parsing theory if he thinks that Pratt parsing was only discovered "in the last few years".