bastikr / boolean.py

Implements boolean algebra in one module.
BSD 2-Clause "Simplified" License
76 stars 34 forks source link

feature request: Add an export method #116

Open showell opened 1 year ago

showell commented 1 year ago

Hello, I recently wrote the following code for a project I am working on:

def export(expr, *, f_and, f_or, f_not, f_symbol):
    def f(expr):
        if type(expr) == boolean.boolean.OR:
            return f_or([f(arg) for arg in expr.args])
        elif type(expr) == boolean.boolean.AND:
            return f_and([f(arg) for arg in expr.args])
        elif type(expr) == boolean.boolean.NOT:
            return f_not([f(arg) for arg in expr.args])
        elif type(expr) == boolean.boolean.Symbol:
            return f_symbol(expr.obj)
        else:
            assert False
    return f(expr)

https://github.com/showell/boolean-py-export-example includes that code, and I describe my use case in a little more detail.

The quick summary is that once boolean.py has done the heavy lifting of simplifying my boolean expression, I want to export the objects into my own data structure. (I understand that the docs suggest to do this by subclassing Symbol, NOT, AND and OR functions, but this feels unnecessarily awkward to me.)

The urgency on my end is pretty low, as I am only using this in a standalone project for now, but I suspect other folks might benefit from the code. If this seems like a worthwhile extension, I can probably submit a PR.

showell commented 1 year ago

(I suppose you could also re-brand my "export" function as a "visit" function. As always, apologies if I have overlooked anything in the docs.)