2

I am working abit with kanren for logical programming and it is completely new to me. I have understood how to maek relationships, but i want to make relationships with multiple features for example fitting this description:

  • Define a relation food and program these facts: avocado, carrot, tomato and broccoli are food.
  • Define a relation color and program these facts: carrot is orange, avocado is green, broccoli is green and tomato is red.
  • Define a relation likes and program these facts: Jeff likes carrot, avocado and baseball, Bill likes avocado and baseball, Steve likes tomato and baseball, Mary likes broccoli and Peter likes baseball.

The first part is quite straight forward, heres what i have so far and i am confident that this is correct.

food = Relation()
color = Relation()
likes = Relation()

fact(food, "avocado")
fact(food, "carrot")
fact(food, "tomato")
fact(food, "broccoli")

The second part is where it gets confusing, but i think it should be correct when i look at the parent example which can be found in the documentation.

fact(color, ("green", "avocado"))
fact(color, ("carrot", "orange"))
fact(color, ("broccoli", "green"))
fact(color, ("tomato", "red"))

The third part is where i am completely lost, this is not correct i think because i tried querying it. Here's what i have so far:

fact(likes, ("Jeff", "avocado", "carrot", "baseball"))
fact(likes, ("Bill", "avocado", "baseball"))
fact(likes, ("Steve", "tomato", "baseball"))
fact(likes, ("Mary", "broccoli"))
fact(likes, ("Peter", "baseball"))

Any suggestions on how to do the third part?

1 Answers1

2
from kanren import Relation, fact, run, var

food = Relation()
color = Relation()
likes = Relation()

fact(food, "avocado")
fact(food, "carrot")
fact(food, "tomato")
fact(food, "broccoli")

fact(color, "avocado",  "green")
fact(color, "carrot",   "orange")
fact(color, "broccoli", "green")
fact(color, "tomato",   "red")

fact(likes, "Jeff",  "avocado")
fact(likes, "Jeff",  "carrot")
fact(likes, "Jeff",  "baseball")
fact(likes, "Bill",  "avocado")
fact(likes, "Bill",  "baseball")
fact(likes, "Steve", "tomato")
fact(likes, "Steve", "baseball")
fact(likes, "Mary",  "broccoli")
fact(likes, "Peter", "baseball")

An example query:

Jeff likes some food and its color is green.

>>> x = var()
>>> run(2, x, likes("Jeff", x), color(x, "green"))
('avocado',)
chansey
  • 1,266
  • 9
  • 20