def logicBased(): x = var() print(run(1, x, eq(x, 5))) z = var() print(run(1, x, eq(x, z), eq(z, 3))) print(run(1, x, eq((1, 2), (1, x)))) print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4)))) z = var('test') print(z) a, b, c = vars(3) print(a) print(b) print(c) parent = Relation() facts(parent, ("Homer", "Bart"), ("Homer", "Lias"), ("Abe", "Homer")) print(run(2, x, parent("Homer", x))) y = var() print(run(1, x, parent(x, y), parent(y, 'Bart'))) def grandparent(x, z): y = var() return conde((parent(x, y), parent(y, z))) print(run(1, x, grandparent(x, 'Bart'))) menu() #calls the menu function (a menu loop)
def locate(): mention = var('mention') post_mention = var('post.mention') return ( (post_mention, (mention,)), [ R['LEMMA'](mention, 'mention'), R['poss'](mention, post_mention), membero(mention, not_used), membero(post_mention, not_used) ] )
def logic_solve(puzzle): """First attempt to solve the puzzle using membero. Works but SLOW...""" words = set() for word in RAW_WORDS: words.add(tuple(word)) vs = kn.vars(len(puzzle)) gs = [] for i, v in enumerate(vs): print(tuple(map(str.lower, puzzle[i]))) gs.append(kn.membero(v, tuple(map(str.lower, puzzle[i])))) gs.append(kn.membero(vs, words)) return kn.run(0, vs, *gs)
def locate(): post_text = var('post.text') prep = var('prep') return ( (post_text, (prep,)), [ one_of(R, prep, {'with'}), R['pobj'](prep, post_text), R['outsideq'](prep), R['insideq'](post_text), membero(prep, not_used), membero(post_text, not_used) ] )
def locate(): like_action = var('like') times = var('times') post_likes = var('post.likes_count') return ( (post_likes, (like_action, times)), [ R['LEMMA'](like_action, 'like'), R['npadvmod'](like_action, times), R['nummod'](times, post_likes), membero(like_action, not_used), membero(times, not_used), membero(post_likes, not_used) ] )
def locate(): with_prep = var('with') with_what = var('with_what') post_likes = var('post.likes_count') return ( (post_likes, (with_what,)), [ R['LEMMA'](with_prep, 'with'), R['pobj'](with_prep, with_what), R['LEMMA'](with_what, 'like'), R['nummod'](with_what, post_likes), membero(post_likes, not_used), membero(with_what, not_used) ] )
def possible(y, x, n): ''' initialize variables''' global grid array = [] ''' initialize for loop and if true there is no number similar to the input number inside the row or column of the grid or board.''' for i in range(0, 9): if grid[y][i] == n: if grid[i][x] == n: return False ''' initialize variables and calculate the index location of the board.''' output = var() x0 = (x // 3) * 3 y0 = (y // 3) * 3 ''' initialize a for loop and store the values inside array''' for i in range(0, 3): for j in range(0, 3): array.append(grid[y0 + i][x0 + j]) ''' Applying Kanren functions into the Sudoku algorithm. The functions are use to implement a logic program to verify whether the input variable is identical to the numbers inside the array. If there is no numbers identical to the numbers inside the array, then the function will return True.''' find_number = run(1, output, eq(output, n), membero(output, array)) if len(find_number) != 0: return False return True
def locate(): mention = var('mention') prep = var('prep') post_mention = var('post.mention') return ( (post_mention, (mention, prep)), [ one_of(R, mention, {'mention'}), R['prep'](mention, prep), one_of(R, prep, {'of'}), R['pobj'](prep, post_mention), membero(mention, not_used), membero(post_mention, not_used), membero(prep, not_used) ] )
def locate(): action = var('action') reply = var('reply') post_replies = var('post.repliesCount') reply_syns = {'reply', 'comment'} return ( (post_replies, (reply,)), [ conde((R['dobj'](action, reply),), (R['pobj'](action, reply),)), one_of(R, reply, reply_syns), R['nummod'](reply, post_replies), membero(reply, not_used), membero(post_replies, not_used) ] )
def locate(): post_text = var('post.text') post = var('post') post_syns = {'message', 'content', 'post'} contain = var('contain') return ( (post_text, (contain, post_text)), [ one_of(R, post, post_syns), R['LEMMA'](contain, 'contain'), conde((R['relcl'](post, contain),), (R['acl'](post, contain),)), R['oprd'](contain, post_text), membero(contain, not_used), membero(post_text, not_used) ] )
def eval_expro(expr, env, value, depth=0, maxdepth=3): # logger.debug("Evaluating expr {} to {} with env {}".format(expr, value, env)) uuid = str(uuid4())[:4] if isinstance(expr, ast.AST): logger.info("Found AST for expr -> {}".format( ast_dump_if_possible(expr))) if isinstance(value, ast.AST): logger.info("Found AST for value -> {}".format( ast_dump_if_possible(value))) if depth >= maxdepth: return fail # fmt: off return conde( (eq(expr, ast.Name(id=var('name_' + uuid), ctx=ast.Load())), lookupo(var('name_' + uuid), env, value)), # (lany( # typeo(value, int), # typeo(value, str), # ), # eq(expr, ast.Constant(value=value)),), (eq(expr, ast.Str(s=var('str_e_' + uuid))), typeo( value, str), eq(var('str_e_' + uuid), value)), (eq(expr, ast.Num(n=value)), membero(value, [_ for _ in range(5)])), (eq( expr, ast.BinOp(left=var('e1_' + uuid), op=var('op_e_' + uuid), right=var('e2_' + uuid))), typeo(var('v1_' + uuid), int), typeo(var('v2_' + uuid), int), eval_expro(var('e1_' + uuid), env, var('v1_' + uuid), depth + 1, maxdepth), eval_expro(var('e2_' + uuid), env, var('v2_' + uuid), depth + 1, maxdepth), eval_opo(var('op_e_' + uuid), var('op_v_' + uuid), var('v1_' + uuid), var('v2_' + uuid), value), binopo(var('v1_' + uuid), var('v2_' + uuid), value, op=var('op_v_' + uuid))), # Lists (eq(expr, ast.List(elts=var("list_elements_" + uuid), ctx=ast.Load())), eval_expr_listo(var("list_elements_" + uuid), env, value, depth, maxdepth)), # Functions (eq(expr, ast.Lambda(body=var('body_' + uuid), args=[])), typeo(value, FunctionType), eval_expro(var('body_' + uuid), env, var('body_v_' + uuid), depth + 1, maxdepth), eq(lambda: var('body_v_' + uuid), value)), (eq(expr, ast.Call(func=var('func_' + uuid), args=[], keywords=[])), typeo(var('func_v_' + uuid), FunctionType), eval_expro(var('func_' + uuid), env, var('func_v_' + uuid), depth + 1, maxdepth), applyo(var('func_v_' + uuid), [], value)), )
def locate(): action = var('action') post_text = var('post.text') return ( (post_text, (action,)), [ R['LEMMA'](action, 'contain'), R['dobj'](action, post_text), membero(post_text, not_used) ] )
def locate(): about = var('about') post_text = var('post.text') return ( (post_text, (about,)), [ R['LEMMA'](about, 'about'), R['pobj'](about, post_text), membero(post_text, not_used) ] )
def locate(): post_sentiment = var('post.sentiment') sentiment = var('sentiment') return ( (post_sentiment, (sentiment,)), [ R['LEMMA'](sentiment, 'sentiment'), R['amod'](sentiment, post_sentiment), membero(post_sentiment, not_used) ] )
def locate(): post_count = var('post.count') post = var('post') post_syns = {'message', 'content', 'post'} return ( (post_count, ()), [ one_of(R, post, post_syns), R['nummod'](post, post_count), membero(post_count, not_used) ] )
from kanren import run, membero, var x = var() sol = run(1, x, membero(x, [1, 2, 3]), membero(x, [2, 3, 4])) print(sol)
# Program Author: Kaleb Newsom # Course: CS 351 Programming Languages # Assignment: Logic Programming Lab 2 # import logic methods from kanren from kanren import run, var, membero import random # import package that creates random numbers x = list(range(1, 70)) # set x to a list of numbers from 1 to 69 inclusive y = list(range(1, 27)) # set y to a list of numbers from 1 to 26 inclusive random.shuffle( x) # randomly shuffle the list of numbers from 1 to 69 inclusive random.shuffle(y) # randomly shuffle the list of numbers from 1 to 26 z = var() # let z be a logic variable # let user know that the following statement will be the first 5 powerball numbers print( 'These are your first 5 randomly chosen numbers to select on your powerball ticket!' ) # display a tupple containing the first 5 numbers of the randomized list of numbers including numbers 1 to 69 inclusive print( sorted( run(5, z, membero(z, x), membero(z, x), membero(z, x), membero(z, x), membero(z, x)))) # let user know that the following statement will be the 6th powerball number print( 'This is your randomly chosen 6th powerball number to select on your powerball ticket!' ) # display a tupple containing the 6th powerball number print(sorted(run(1, z, membero(z, (y)))))
#project 2-Author: Luke Landon- import kanren from kanren import run, eq, membero, var, conde, Relation, facts import random x = kanren.var() print(run(1, x, eq(x, 5))) #asks for a number x such that x is equal to z and z is equal to 3 z = kanren.var() print(run(1, x, eq(x, z), eq(z, 3))) #asks for a number x such that 1,2 equals 1,x print(run(1, x, eq((1, 2), (1, x)))) #uses membero twice to ask for 2 values of x such that x is a member of 1,2,3 and that x is a member of 2,3.4 print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4)))) #creates a logic variable z = kanren.var('test') print(z) #creates multiple logic variables at once a, b, c = var('a'), var('b'), var('c') print(a) print(b) print(c) #creates a parent relationship and uses it to state facts about who is related to who parent = Relation() facts(parent, ("Homer", "Bart"), ("Homer", "Lisa"), ("Abe", "Homer")) print(run(1, x, parent(x, "Bart"))) print(run(2, x, parent("Homer", x))) #uses intermediate variables for complex queries y = var() print(run(1, x, parent(x, y), parent(y, 'Bart')))
) # 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)) print("Take $10 from anyone with more than $100") print(run(0, target, tax_the_rich)) print("Give $10 to theorists") print(run(0, target, theorist_bonus))
# Michael Martindill # CS 351 # 2/7/2019 # The purpose of this program is to find the union of two sets by using logic programming with the kanren package from kanren import run, eq, membero, var, conde # Function to convert the inputted string into an array def stringToArray(str): setArray = str.split(',') return setArray print( "Input two sets of numbers to find the union between them. (Separated by commas)" ) set1 = input("Set 1: ") set1 = set1.replace(" ", "") set1Array = stringToArray(set1) set2 = input("Set 2: ") set2 = set2.replace(" ", "") set2Array = stringToArray(set2) x = var() print("The union of these two sets is: ") print(run(len(set1Array), x, membero(x, set1Array), membero(x, set2Array)))
# optional name strings are helpful for debugging first = var(prefix="first") last = var(prefix="last") ident = var(prefix="ident") balance = var(prefix="balance") newbalance = var(prefix="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), applyo(add, (10, balance), newbalance), ) # Take $10 from anyone with more than $100 a = var(prefix="a") tax_the_rich = lall( membero(source, accounts), applyo(gt, (balance, 100), a), eq(a, True), applyo(sub, (balance, 10), newbalance), ) print("Take $10 from anyone with more than $100") print(run(0, target, tax_the_rich))
run(1, x, eq(x, 5)) print (run(1, x, eq(x, 5))) # Multiple variables and multiple goals can be used simultaneously print ("\n [2] Multiple variables:") z = var() print(run(1, x, eq(x, z), eq(z, 3))) # unification, an advanced form of pattern matching print ("\n [3] unification:") print (run(1, x, eq((1, 2), (1, x)))) # Member usage print ("\n [1] equal:") print(run(2, x, membero(x, (1, 2, 3)), # x is a member of (1, 2, 3) membero(x, (2, 3, 4)))) # x is a member of (2, 3, 4) # Logic variable z = var('test') print (z) # Multiple variable at one a, b, c = var('a'), var('b'), var('c') print(a) print(b) print(c) # Data store and relationship parent = Relation() facts(parent, ("Homer", "Bart"),
def left(q, p, list): return membero((q,p), zip(list, list[1:]))
def one_of(R, idx, lst): l = var('l'+str(idx)) return conde((R['LEMMA'](idx, l), membero(l, lst)))