Expeirment - 9
Expeirment - 9
Structure
Let’s talk about facts and rules. Facts are true statements — say, Bucharest
is the capital of Romania. Rules are constraints that lead us to conclusions
about the problem domain. These are logical clauses that express facts. We
use the following syntax to write a rule (as a clause):
H -> B1, …, Bn.
We can read this as:
H if B1 and … and Bn.
Here, "H" is the head of the rule and "B1, …, Bn" is the body. A fact is a rule
with no body:
H.
An example would be:
fallible(X) -> human(X)
Every logic program needs facts based on which to achieve the given goal.
Rules are constraints that get us to conclusions.
The following Python code will help you match a mathematical expression
−
Consider importing the following packages first –
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative
pyDatalog.create_terms('X,Y')
Queries can contain several variables and several criteria ('&' is read 'and'):
def twice(a):
return a+a
pyDatalog.create_terms('twice')
print((X==1) & (Y==twice(X)))
X|Y
--|--
1|2
Loops
Let's first declare the Variables we'll need:
A loop can be created by using the .in() method (we'll see that there are
other ways to create loops later):
for x in range(5):
print(x)
0
1
2
3
4
Logic Functions :
A function defines one value for a given argument. It is similar to a python
dictionary.
A function can be queried.
from pyDatalog import pyDatalog
pyDatalog.create_terms('X,Y,Z, salary, tax_rate, tax_rate_for_salary_above,
net_salary')
salary['foo'] = 60
salary['bar'] = 110
# give me all the X and Y so that the salary of X is Y
print(salary[X]==Y)
X|Y
----|----
bar | 110
foo | 60
# python equivalent:
_salary = dict()
_salary['foo'] = 60
_salary['bar'] = 110
print(_salary.items())
[('foo', 60), ('bar', 110)]