Parsing is much simpler than you think!

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

This is the technique jon blow recently presented right? Its a nice concise description of it.

krystofjakubek
Автор

Recursion is a good way to think about this problem. What I believe you are trying to describe is called "recursive descent parsing". Commonly described using context-free grammar rules which are similar to more commonly known regular expressions.
Addition and subtraction with parentheses and unary negation would look like this:

A = M ('+' M)*
M = T ('*' T)*
T = ('-'|) (number | '(' A ')')
(* means the previous term can be repeated none to any times and | imeans that an expression from either side can occur there)

A representing an additive expression, M a multiplicative expression, and T a term expression. Each expression has its own function returning a numerical value.
The parser would evaluate the input as an additive expression. When encountering M, it would recursively call the evaluation of the multiplicative expression, and again with T. The third function now either reads a number or open parenthesis, in the latter case recursing once again to the top before reading the closing parenthesis.
Returning from a function will occur when the regular expression no longer fits the input (ie. in M when there is no '*' after returning from T). The A and M terms then accumulate the returned values.


This blew my mind when I learned about this from a homework assignment, especially how simple it was to implement. Shame it is so rarely talked about.

hhehe
Автор

i think there is value in the shunting yard method too, especially if you are writing an encoder rather than an interpreter.

androth
Автор

2:33 Pretty sure that 4+5*6 is not 34 factorial (sarcasm)

alexdiezg
Автор

Parsing is insanely easy... it just becomes kinda tedious. Definitely not as tedious as a lexer or a code analyzer though. 😅

oglothenerd
Автор

Now talk about type checking/inference next :P

omega_sine
Автор

Thank you. I humbly ask for one more favor: script your videos. They do have real substance, but are rather difficult to listen/follow.

toomasvendelin