News for hackers. Stuff that matters.
Re:Just Write the Parser by musicale on Wednesday October 21, 2020 @06:51PM (#24853133)
What's the best way to handle unary "-" and other unary operators?

I'd like to be able to write expressions like "-2^-(2+2)" or "a cos b + a sin b".

For "-2^-(2+2)" note that exponentiation has higher precedence than negation.

Re:Just Write the Parser by musicale on Wednesday October 21, 2020 @10:42PM (#24854408)
Thanks for the other replies, but I was asking the original author for a suggestion using the presented framework, rather than an alternate algorithm or approach from someone else. As presented, the approach didn't seem to handle unary operators.

I probably should have noted that I am already familiar with Pratt parsing, which seems like something that isn't actually brain-dead simple and obvious in the same way (which is why it was worth writing a paper about in the 1970s.)

Hoping for a reply from the original author to recommend a simple approach to add unary operators.

Re:Just Write the Parser by tiarkrompf on Thursday October 22, 2020 @02:23PM (#24861407)
Great question! Unary operators are really simple to add: you just look for the operator symbol first thing at the right level of precedence. Same idea as "if (peek == '(') ..." for parentheses, but outside the code that deals with '*' and '^' (if you want those to bind more strongly).
Re:Just Write the Parser by thysultan on Wednesday October 21, 2020 @08:40PM (#24853855)
Take the current + next node

i.e: parse_node + parse_peek

When parse_node is an operator you know it is the "-2" in "-2^-2(2+2)" and when parse_peek is the operator it is "-(2+2)" in the same. An example of this:

- https://github.com/thysultan/Ally/blob/8ba0b4de7ab104ceae54d...

Re:Just Write the Parser by musicale on Wednesday October 21, 2020 @10:52PM (#24854455)
1) This reference is cryptic

2) I was asking the original author for a simple extension to the presented appraoch

Re:Just Write the Parser by myk9001 on Wednesday October 21, 2020 @07:24PM (#24853392)
Take a look at "Parsing expressions by precedence climbing"[1] by Eli Bendersky.

See the "Other resources" section for other approaches to this problem.

1: https://eli.thegreenplace.net/2012/08/02/parsing-expressions...

Re:Just Write the Parser by musicale on Wednesday October 21, 2020 @10:50PM (#24854450)
1) Like the original article, this leaves unary operators as an exercise for the reader (though it does note so explicitly and provides a small hint)

2) This looks more like Pratt parsing vs. the approach described in the article

3) I was asking the original author