Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active June 24, 2023 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/e1f605addfedef45604f2c587dfe083c to your computer and use it in GitHub Desktop.
Save dacr/e1f605addfedef45604f2c587dfe083c to your computer and use it in GitHub Desktop.
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/29adce8710cd38b0e5e1fe67e682888ed64cc5e
// 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 : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : d0bf6eb4-acb7-49b9-bb54-edd6d63f3572
// created-on : 2019-10-04T16:36:54+02:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.0"
//> using dep "fr.janalyse::drools-scripting:1.1.0"
//> using dep "org.scalatest::scalatest:3.2.16"
// ---------------------
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