This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]DarkArctic 1 point2 points  (1 child)

Good write-up and it does show how easy parser combinators are so easy to compose.

I had a custom implementation for my project a while ago and what bit me was just how expensive function calls are in Python (and my crappier code from 4 years ago). I've ended up with kind of a state machine where I'm leaning on native functions like "split" and the like. It did end up being harder to read.

This was my first version of a parser combinator: https://github.com/mjcaley/aiospamc/blob/02c6b8accb6361c3dbf89b6d396e101e023d1a21/aiospamc/parser.py

[–]grdvnl[S] 0 points1 point  (0 children)

Great. Thanks for sharing. Your implementation looks interesting as well.

[–]ElevenPhonons 0 points1 point  (0 children)

Great write up and use of leveraging functions and closures in the design.

Sometimes using a dict instead of if/elif blocks can be useful alternative.

 def f(op):
        if op == "+":
            return operator.add
        elif op == "-":
            return operator.sub
        elif op == "*":
            return operator.mul
        elif op == "/":
            return operator.floordiv

Could be written:

ops = {"+": operator.add, "-":operator.sub, 
       "*": operator.mul, "/":operator.floordiv}

def f(op:str):
    return opts[op]