开发者

Symbolic manipulation over non-numeric types

I'm interested in a python library that permits symbolic manipulation where the symbols and can be unknowns of an arbitrary type.

This is the code that I want to write:

>>> myexpression = symbol("foo") == "bar"
>>> print myexpression
foo == "bar"
>>> print myexpression(foo="quux")
False
>>> myexpression.or_(True)
True

Or some rough approximation of that. It开发者_JAVA技巧 doesn't actually even need to be that clever, I'd be happy enough having to call a lot of extra introspection methods to get something like the above (for instance, even if the logical tautology is not directly simplified)

My first instinct was to look at sympy, but it seems that library makes the strong assumption that symbolic variables must be numbers; and I'd like to at least operate on sequences and sets:

>>> myexpression = sympy.Eq(sympy.Symbol("foo"), 5)
>>> myexpression
foo == 5
>>> myexpression = sympy.Eq(sympy.Symbol("foo"), "bar")
Traceback (most recent call last):
  ...
sympy.core.sympify.SympifyError: SympifyError: 'bar'

Is there a way to get sympy to understand non-numeric variables, or another library that can do similar things?


Not sure how well it fits the uses you have in mind, but the nltk (Natural Language Toolkit) has modules for symbolic manipulation, including first order logic, typed lambda calculus, and a theorem prover. Take a look at this howto.


Could you just map everything into a Sympy symbol? For instance, in your last expression: sympy.Eq(sympy.Symbol("foo"), sympy.Symbol("bar")). Or do you mean you actually want to write logical statements about set relationships?


Boolean logic is in SymPy although not as easily expressible as it should be. Its definitely there though.

In [1]: x,y,z = symbols('x y z')
In [2]: A = Eq(x,y)
In [3]: A
Out[3]: x = y

In [4]: B = Gt(y,z)
In [5]: And(A,B)
Out[5]: x = y ∧ y > z

In [6]: C = Gt(x,z)
In [7]: And(A, Or(B,C))
Out[7]: x = y ∧ (y > z ∨ x > z)

I'm not aware of many methods to simplify these expressions. This is the sort of thing that would be easy to do if there was interest though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜