示例#1
0
from kanren import run, eq, membero, var, conde
z = var()
x = var()
run(1, x, eq(x, z), eq(z, 3))
print(run(1, x, eq(x, z), eq(z, 3)))
示例#2
0
from kanren import Relation, facts, run, var
x = var()  #declaring x variable with var
parent = Relation()
#presenting the fact in the system
facts(parent, ("Nathan", "Mexican"), ("Tina", "Thai"), ("Tim", "Vegetarian"),
      ("Sally", "Italian"), ("John", "Thai"))

#setting the parameter and the output
Thai_food = run(2, x, parent(x, "Thai"))
print(Thai_food)

mexican_food = run(1, x, parent(x, "Mexican"))
print(mexican_food)

veg_food = run(1, x, parent(x, "Vegetarian"))
print(veg_food)

Italian_food = run(1, x, parent(x, "Italian"))
print(Italian_food)
示例#3
0
def grandparent(gparent, child):
    p = var()
    return conde((parent(gparent, p), parent(p, child)))
def grandparent(x, y):
    temp = var()
    return conde((parent(x, temp), parent(temp, y)))
def uncle(x, y):
    temp = var()
    return conde((father(temp, x), grandparent(temp, y)))
示例#6
0
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative

# Define some dummy Operationss
add = 'add'
mul = 'mul'
# Declare that these ops are commutative using the facts system
fact(commutative, mul)
fact(commutative, add)
fact(associative, mul)
fact(associative, add)

# Define some wild variables
x, y = var('x'), var('y')

# Two expressions to match
pattern = (mul, (add, 1, x), y)                # (1 + x) * y
expr    = (mul, 2, (add, 3, 1))                # 2 * (3 + 1)
print(run(0, (x,y), eq(pattern, expr)))        # prints ((3, 2),) meaning
                                               #   x matches to 3
                                               #   y matches to 2
示例#7
0
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative

add = 'add'
mul = 'mul'

fact(commutative, mul)
fact(commutative, add)
fact(associative, mul)
fact(associative, add)

x, y = var('x'), var('y')

pattern = (mul, (add, 1, x), y)
expr = (mul, 2, (add, 3, 1))
print(run(0, (x, y), eq(pattern, expr)))
 def test_ast_string_results_in_var_string(self):
     ret, _ = self.run_expr(ast.Str(s="Hello world!"), var())
     self.assertEqual(ret[0], "Hello world!")
 def test_string_value_results_in_ast_string(self):
     ret, _ = self.run_expr(var(), "Hello world!", eval_expr=True, n=1)
     self.assertIn(type(ret[0]), [ast.Str, ast.Constant])  # Can be Constant in 3.8+
     self.assertEqual(ret[0].s, "Hello world!")
 def test_ast_modulo_results_in_var_integer(self):
     ret, _ = self.run_expr(
         ast.BinOp(left=ast.Num(n=3), op=ast.Mod(), right=ast.Num(n=2)), var()
     )
     self.assertEqual(ret[0], 1)
 def test_ast_modulo_with_rhs_zero_is_not_picked_up(self):
     ret, _ = self.run_expr(
         ast.BinOp(left=ast.Num(n=3), op=ast.Mod(), right=ast.Num(n=0)), var()
     )
     self.assertEqual(len(ret), 0)
 def test_ast_multiplication_results_in_var_integer(self):
     ret, _ = self.run_expr(
         ast.BinOp(left=ast.Num(n=2), op=ast.Mult(), right=ast.Num(n=1)), var()
     )
     self.assertEqual(ret[0], 2)
 def test_ast_subtraction_results_in_var_integer(self):
     ret, _ = self.run_expr(
         ast.BinOp(left=ast.Num(n=1), op=ast.Sub(), right=ast.Num(n=1)), var()
     )
     self.assertEqual(ret[0], 0)
示例#14
0
文件: states.py 项目: logpy/logpy
coastal_states = 'WA,OR,CA,TX,LA,MS,AL,GA,FL,SC,NC,VA,MD,DE,NJ,NY,CT,RI,MA,ME,NH,AK,HI'.split(',')

for state in coastal_states:        # ['NY', 'NJ', 'CT', ...]
    fact(coastal, state)            # e.g. 'NY' is coastal

with open('examples/data/adjacent-states.txt') as f: # lines like 'CA,OR,NV,AZ'
    adjlist = [line.strip().split(',') for line in f
                                       if line and line[0].isalpha()]

for L in adjlist:                   # ['CA', 'OR', 'NV', 'AZ']
    head, tail = L[0], L[1:]        # 'CA', ['OR', 'NV', 'AZ']
    for state in tail:
        fact(adjacent, head, state) # e.g. 'CA' is adjacent to 'OR',
                                    #      'CA' is adjacent to 'NV', etc...

x = var()
y = var()

print((run(0, x, adjacent('CA', 'NY')))) # is California adjacent to New York?
# ()

print((run(0, x, adjacent('CA', x))))    # all states next to California
# ('OR', 'NV', 'AZ')

print((run(0, x, adjacent('TX', x),    # all coastal states next to Texas
                coastal(x))))
# ('LA',)

print((run(5, x, coastal(y),           # five states that border a coastal state
                adjacent(x, y))))
# ('VT', 'AL', 'WV', 'DE', 'MA')
示例#15
0
文件: corleone.py 项目: logpy/logpy
def grandparent(gparent, child):
    p = var()
    return conde((parent(gparent, p), parent(p, child)))
 def test_ast_name_results_in_lookup_from_env(self):
     ret, _ = self.run_expr(ast.Name(id="x", ctx=ast.Load()), var(), env=[["x", 1]])
     self.assertEqual(ret[0], 1)
示例#17
0
#!/usr/bin/env python
# coding: utf-8

# In[15]:


from kanren import Relation, facts, run, conde, var, eq

x = var()
y = var()

father = Relation()
mother = Relation()

facts(father, ('The Force', 'Anakin Skywalker'),
 ('Cliegg Lars', 'Owen Lars'),
 ('Anakin Skywalker', 'Leia Organa'),
 ('Anakin Skywalker', 'Luke Skywalker'),
 ('Han Solo', 'Ben Solo'))

facts(mother, ('Shmi Skywalker', 'Anakin Skywalker'),
 ('Shmi Skywalker', 'Owen Lars'),
 ('Padme Amidala', 'Leia Organa'),
 ('Padme Amidala', 'Luke Skywalker'),
 ('Leia Organa', 'Ben Solo'))

resultF = run(1, x, father(x, 'Anakin Skywalker'))
resultM = run(1, x, mother(x, 'Anakin Skywalker'))
print(resultF + resultM)

resultF = run(1, x, father(x, 'Owen Lars'))
 def test_ast_lambda_without_args_results_in_function_type(self):
     ret, _ = self.run_expr(ast.Lambda(args=[], body=ast.Num(n=1)), var(), env=[])
     self.assertEqual(type(ret[0]), FunctionType)
示例#19
0
def Grandparent(grand_parent, child):
    parent = var()
    return conde((Parent(grand_parent, parent), Parent(parent, child)))
 def test_number_value_results_in_ast_number(self):
     ret, _ = self.run_expr(var(), 1, eval_expr=True)
     self.assertIsInstance(ret[0], ast.Num)
## expression matcher
from kanren import run, var, fact
import kanren.assoccomm as la

add = 'addition'
mul = 'multiplication'

fact(la.commutative, mul)
fact(la.commutative, add)
fact(la.commutative, mul)
fact(la.commutative, add)

a, b, c = var('a'), var('b'), var('c')

# (3*(-2)) + ((1+2*3)*(-1))
expression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))
# (1 + (2*a))*b + 3*c
expression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))
# c*3 + b*(2*a + 1)
expression2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))
# 2*a*b + b + 3*c
expression3 = (add, (add, (mul, (mul, 2, a), b)), (mul, 3, c))

print(run(0, (a, b, c), la.eq_assoccomm(expression1, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression2, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression3, expression_orig)))

## Check prime number
import itertools as it
from kanren import isvar, membero, var, run, eq
from kanren.core import success, fail, condeseq
 def test_ast_empty_list_evaluates_to_empty_list(self):
     ret, goals = self.run_expr(
         ast_expr=ast.List(elts=[], ctx=ast.Load()),
         value=var(),
     )
     self.assertEqual(ret[0], [])
def sibling(x, y):
    temp = var()
    return conde((parent(temp, x), parent(temp, y)))
示例#24
0
'''
Name: Leouel Guanzon
Professor: Cary Jardin
Course: CS351 Programming Languages
Description: Logical Programming (Simple Family Tree) 
'''

from kanren import run, var, Relation, facts

parent = Relation()
member = var()

dad = input("Enter your father's name: ")
child1 = input("Enter your brother's/sister's name: ")
child2 = input("Enter your name: ")

facts(parent, (dad, child1), (dad, child2))

print("The father of ", child1, " is ")
print(run(1, member, parent(member, child1)))
print("The children of ", dad, " is ")
print(run(2, member, parent(dad, member)))
 def test_expression_doesnt_change_env(self):
     ret, _ = self.run_stmt(ast_expr=ast.Expr(value=ast.Num(n=1)),
                            value=var())
     self.assertEqual(ret[0], [])
示例#26
0
from account import Account
from kanren import unifiable, run, var, eq, membero, variables
from kanren.core import lall
from kanren.arith import add, gt, sub, lt

unifiable(Account)  # Register Account class

accounts = (Account('Adam', 'Smith', 1,
                    20), Account('Carl', 'Marx', 2,
                                 3), Account('John', 'Rockefeller', 3, 1000))

# optional name strings are helpful for debugging
first = var('first')
last = var('last')
ident = var('ident')
balance = var('balance')
newbalance = var('newbalance')

# Describe a couple of transformations on accounts
source = Account(first, last, ident, balance)
target = Account(first, last, ident, newbalance)

theorists = ('Adam', 'Carl')
# Give $10 to theorists
theorist_bonus = lall((membero, source, accounts), (membero, first, theorists),
                      (add, 10, balance, newbalance))

# Take $10 from anyone with more than $100
tax_the_rich = lall((membero, source, accounts), (gt, balance, 100),
                    (sub, balance, 10, newbalance))
示例#27
0
)

facts(
    mother,
    ("Carmela", "Michael"),
    ("Carmela", "Sonny"),
    ("Carmela", "Fredo"),
    ("Kay", "Mary"),
    ("Kay", "Anthony"),
    ("Sandra", "Francesca"),
    ("Sandra", "Kathryn"),
    ("Sandra", "Frank"),
    ("Sandra", "Santino"),
)

q = var()

print((run(0, q, father("Vito", q))))  # Vito is the father of who?
# ('Sonny', 'Michael', 'Fredo')

print((run(0, q, father(q, "Michael"))))  # Who is the father of Michael?
# ('Vito',)


def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])


print((run(0, q, parent(q, "Michael"))))  # Who is a parent of Michael?
# ('Vito', 'Carmela')
示例#28
0
from kanren import run, eq, membero, var, conde
x = var()
run(1, x, eq(x, 5))
print (run(1, x, eq(x, 5)))
示例#29
0
def sibling(a, b):
    p = var()
    return conde((parent(p, a), parent(p, b)))
示例#30
0
facts(edges, (1, 'U', 1), (2, 'U', 2), (3, 'U', 3), (4, 'U', 1), (5, 'U', 2),
      (6, 'U', 3), (7, 'U', 4), (8, 'U', 5), (9, 'U', 6), (1, 'D', 4),
      (2, 'D', 5), (3, 'D', 6), (4, 'D', 7), (5, 'D', 8), (6, 'D', 9),
      (7, 'D', 7), (8, 'D', 8), (9, 'D', 9), (1, 'R', 2), (2, 'R', 3),
      (3, 'R', 3), (4, 'R', 5), (5, 'R', 6), (6, 'R', 6), (7, 'R', 8),
      (8, 'R', 9), (9, 'R', 9), (1, 'L', 1), (2, 'L', 1), (3, 'L', 2),
      (4, 'L', 4), (5, 'L', 4), (6, 'L', 5), (7, 'L', 7), (8, 'L', 7),
      (9, 'L', 8))

# def walk(pos, path, end_pos):
#     x = var()
#     lany(lall(eq(path, []), eq(pos, end_pos)),
#          lall(
#               edges(pos, path[0], x),
#               walk(x, path[1:], end_pos)))


def walk(pos, path, end_pos):
    if eq(path, []):
        eq(pos, end_pos)
        return success
    else:
        x = var()
        return conde(edges(pos, path[0], x), walk(x, path[1:], end_pos))


x = var('x')
y = var('y')
print(run(1, y, walk(5, ['L', 'L', 'U'], x), walk(y, [], x)))  # 3
示例#31
0
文件: corleone.py 项目: logpy/logpy
              ('Sonny', 'Francesca'),
              ('Sonny', 'Kathryn'),
              ('Sonny', 'Frank'),
              ('Sonny', 'Santino'))

facts(mother, ('Carmela', 'Michael'),
              ('Carmela', 'Sonny'),
              ('Carmela', 'Fredo'),
              ('Kay', 'Mary'),
              ('Kay', 'Anthony'),
              ('Sandra', 'Francesca'),
              ('Sandra', 'Kathryn'),
              ('Sandra', 'Frank'),
              ('Sandra', 'Santino'))

q = var()

print((run(0, q, father('Vito', q))))          # Vito is the father of who?
# ('Sonny', 'Michael', 'Fredo')


print((run(0, q, father(q, 'Michael'))))       # Who is the father of Michael?
# ('Vito',)

def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])


print((run(0, q, parent(q, 'Michael'))))       # Who is a parent of Michael?
# ('Vito', 'Carmela')
from kanren import run, var
from kanren import Relation, facts

I = var()  # Ingrediente
P = var()  # Plato
T = var()  # Tipo de plato
M = var()  # Malestar

es_ingred_de = Relation()
facts(es_ingred_de, ("tomate", "ensalada"), ("limon", "ensalada"),
      ("pollo", "aguadito"), ("arvejas", "aguadito"), ("zapallo", "picante"),
      ("cebolla", "picante"), ("maracuya", "helado"),
      ("saborizante", "helado"), ("aguardiente", "calientito"),
      ("te", "calientito"))

##TIPO DE ALIMENTOS
es_un_tipoalimento_de = Relation()
facts(es_un_tipoalimento_de, ("ensalada", "entrada"), ("aguadito", "sopa"),
      ("picante", "platofondo"), ("helado", "postre"),
      ("calientito", "bebida"))

##RECOMENDADO PARA
bueno_contra = Relation()
facts(bueno_contra, ("tomate", "caries"), ("limon", "gripe"),
      ("cebolla", "gripe"), ("zanahoria", "ceguera"), ("te", "stress"),
      ("maracuya", "stress"))
##EXCESO
#en_exceso_provoca(huevo, colesterol)
#en_exceso_provoca(platano, diabetes)
#en_exceso_provoca(carne, artritis)
#en_exceso_provoca(aceite, colesterol)
示例#33
0
文件: corleone.py 项目: logpy/logpy
def sibling(a, b):
    p = var()
    return conde((parent(p, a), parent(p, b)))
示例#34
0
from kanren import run, eq, membero, var, conde, Relation, facts

# specify the relation we wish to build (its parent in our case)
Parent=Relation()

# adding facts given in Question 1 - Modelling the knowledge
facts (Parent, ('Leia Organa', 'Kylo Ren'),
               ('Darth Vader', 'Leia Organa'),
               ('Darth Vader', 'Luke Skywalker'),
               ('Han Solo',  'Kylo Ren'))


# running queires in Question 2

# define parent variable
parent_l_s = var()
print "Who is the parent of Luke Skywalker :"
print(run(0, parent_l_s, Parent(parent_l_s, 'Luke Skywalker')))

# define child variable
children_d_v=var()
print "Who are the children of Darth Vader :"
print(run(0, children_d_v, Parent('Darth Vader', children_d_v)))

# grandparent Relation
def Grandparent(grand_parent, child):
    parent = var()
    return conde((Parent(grand_parent, parent), Parent(parent, child)))

# get answer to part 3
parent = var()
示例#35
0
def grandfather(x, z):
     y = var()
     return conde((father(x, y), father(y, z)))
示例#36
0
from account import Account
from kanren import unifiable, run, var, eq, membero, variables
from kanren.core import lall
from kanren.arith import add, gt, sub

unifiable(Account)  # Register Account class

accounts = (Account('Adam', 'Smith', 1, 20),
            Account('Carl', 'Marx', 2, 3),
            Account('John', 'Rockefeller', 3, 1000))

# optional name strings are helpful for debugging
first = var('first')
last = var('last')
ident = var('ident')
balance = var('balance')
newbalance = var('newbalance')

# Describe a couple of transformations on accounts
source = Account(first, last, ident, balance)
target = Account(first, last, ident, newbalance)

theorists = ('Adam', 'Carl')
# Give $10 to theorists
theorist_bonus = lall((membero, source, accounts),
                      (membero, first, theorists),
                      (add, 10, balance, newbalance))

# Take $10 from anyone with more than $100
tax_the_rich = lall((membero, source, accounts),
                    (gt, balance, 100),