View Source Family Tree

Mix.install([
  {:guesswork, "~> 0.4"}, 
  {:kino, "~> 0.13"}
], 
  consolidate_protocols: false
)

Build Knowledge Base

import Guesswork.Ast

alias Guesswork.Ast.And
alias Guesswork.Ast.Fact
alias Guesswork.Answer.Result

Start by adding rules and concrete facts to the knowledge base, in this case parent child relationships and grandparents defines as parent relationships.

defmodule KB do
  use Guesswork.KnowledgeBase.Collection

  deffact("parent", [:bob, :joe])
  deffact("parent", [:bob, :jean])
  deffact("parent", [:mary, :joe])
  deffact("parent", [:bobby, :jean])

  deffact("parent", [:christy, :bob])
  deffact("parent", [:lance, :bob])

  deffact("parent", [:billy, :christy])
  deffact("parent", [:meg, :lanceb])

  defrule("grandparent", [gp, gc], 
    And.new([Fact.new("parent", [gp, p]), Fact.new("parent", [p, gc])]))
end

Query the System

Now you can query the system. This first query is simplier since it only asks questions of the concrete facts stored in the knowledge base; in this case what are bob's children.

Guesswork.query(term(Fact.new("parent", [:bob, child])), 10, knowledge_base: KB)

You can also ask more complex questions, like what are all the grandparents of joe. You can also see that when a result is returned all the bound variables are returned, so you can easily debug where relationships were found.

Guesswork.query(term(Fact.new("grandparent", [gp, :joe])), 100, knowledge_base: KB)