Python as Rule Language, first attempt.

Here's a first stab at a Rule Language for pyRete.

>>> import pyrete
>>> @pyrete.rule
... def rulename(val1 = int, val2 = float):
... salience = 10
... if val1 > val2:
... print val1, "is bigger than", val2
I hope none of the above is particularly unclear or cryptic. The above is valid Python syntax but the parsing is done a bit differently. It differs mainly in three ways, described below.

1) The @pyrete.rule statement is a Python function decorator but it's used more as a Java annotation (I don't modify the function in any way). Basically it tags the function with a meta-data value which is used to decide which functions to treat as Rules and which to leave alone.

2) The function arguments (val1 and val2) are considered variables in the if statement's condition. Variable types are specified using default argument values (int and float). If no default value is specified the variable will be considered dynamic and all asserted objects that match the object's usage specification will be passed in for evaluation (aka Duck Typing). You can read more about the consequences of Duck Typing and Rete here and here.

3) An optional assignment to the local variable "salience" can be performed before the if statement. Assigning to any other variable or placing the assignment after the if statement raises a Syntax Error. If no assignment is done a salience value of 0 is used for the Rule. Currently only numbers can be assigned but the idea is to allow dynamic salience by allowing assignment to a global variable, class attribute or function.

I've got about 80% of the RuleParser done, the only problem is that I have to parse Rules from string or file. I can't parse a declared function because there's no way "back" from a compiled function's bytecode to the AST that my function can parse. This means, among other things, that I could introduce special syntax (static typing for variables for example) but I think my little function hack takes care of the problem quite nicely. Also, I really really want to be able to parse compiled functions because it opens up so many possibilties that I'd otherwise have to (re)write code for. Among other things you can use Python's ability to generate functions at run time to construct Rules which is kind of neat.

Inga kommentarer: