Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active Jun 20, 2021
Embed
What would you like to do?
Drools family knowledge base / published by https://github.com/dacr/code-examples-manager #8a6447c0-8777-440a-8635-48f17fc14797/e020898eaafadd3f286c58f4f099e3383e3a878
// summary : Drools family knowledge base
// keywords : scala, drools, mvel, scalatest, ai, knowledgebase, @testable
// publish : gist
// authors : David Crosson
// license : Apache2
// id : 8a6447c0-8777-440a-8635-48f17fc14797
// execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc'
// created-on : 2019-09-27T17:07:21+02:00
import $ivy.`fr.janalyse::drools-scripting:1.0.11`, $ivy.`org.scalatest::scalatest:3.2.6`
import fr.janalyse.droolscripting._, org.scalatest._, flatspec._, matchers._, OptionValues._
object KbTest extends AnyFlatSpec with should.Matchers {
val drl =
"""package test
|dialect "mvel"
|import java.util.LinkedList
|
|declare Someone
| name:String @key
| gender:String // male, female
| age:int
|end
|
|declare ChildOf
| child:Someone
| parent:Someone
|end
|
|declare Mother
| someone:Someone
|end
|
|rule "is mother"
|when
| $someone:Someone(gender=="female")
| LinkedList(size>0) from collect( ChildOf(parent == $someone) )
|then
| insert(new Mother($someone))
|end
|
|""".stripMargin
"Family KB" should "deduce who is parent" in {
val engine = DroolsEngine(drl, DroolsEngineConfig.configWithEquality)
val john = """{"name":"John", "gender":"male", "age":42}"""
val sarah = """{"name":"Sarah", "gender":"female", "age":32}"""
val joe = """{"name":"Joe", "gender":"male", "age":4}"""
val facts = List(
"test.Someone"->john,
"test.Someone"->sarah,
"test.Someone"->joe,
"test.ChildOf"->s"""{"child":$joe, "parent":$sarah}""",
)
facts.foreach{case (kind, json) => engine.insertJson(json, kind)}
engine.fireAllRules()
engine.getObjects should have size(5)
engine.getModelFirstInstance("test.Mother") shouldBe 'defined
}
}
KbTest.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment