Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drools forward chaining example knowledge base with roots from wikipedia definition example / published by https://github.com/dacr/code-examples-manager #d0bf6eb4-acb7-49b9-bb54-edd6d63f3572/883012b22ac2b1e4e145e3093061883bffbe9abf
// summary : Drools forward chaining example knowledge base with roots from wikipedia definition example
// keywords : scala, drools, mvel, scalatest, ai, knowledgebase, @testable
// publish : gist
// authors : David Crosson
// license : Apache2
// id : d0bf6eb4-acb7-49b9-bb54-edd6d63f3572
// execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc'
// created-on : 2019-10-04T16:36:54+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 {
override def suiteName: String = "KBTest"
/* https://en.wikipedia.org/wiki/Forward_chaining
If X croaks and X eats flies - Then X is a frog
If X chirps and X sings - Then X is a canary
If X is a frog - Then X is green
If X is a canary - Then X is yellow
*/
val drl =
"""package test
|dialect "mvel"
|
|declare ItCroaks end
|declare ItEatsFlies end
|declare ItChirps end
|declare ItSings end
|
|declare IsGreen end
|declare IsYellow end
|
|declare IsFrog end
|declare IsCanary end
|
|rule "frog" when ItCroaks() ItEatsFlies() then insert(new IsFrog()) end
|rule "canary" when ItChirps() ItSings() then insert(new IsCanary()) end
|
|rule "all frogs are green" when IsFrog() then insert(new IsGreen()) end
|rule "all canaries are yellow" when IsCanary() then insert(new IsYellow()) end
|""".stripMargin
"Forward chaining KB" should "work" in {
val engine = DroolsEngine(drl)
val facts = List( ("{}", "test.ItCroaks"), ("{}", "test.ItEatsFlies") )
//facts.foreach{case (kind, json) => engine.insertJson(json, kind)}
for { (json, declareType) <- facts } {
engine.insertJson(json, declareType)
}
engine.getModelInstances("test.IsFrog").size shouldBe 0
engine.fireAllRules()
engine.getModelInstances("test.IsFrog").size shouldBe 1
}
}
KbTest.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment