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/3b7a586ca28eddba389d291fe814a7e8 to your computer and use it in GitHub Desktop.
Save dacr/3b7a586ca28eddba389d291fe814a7e8 to your computer and use it in GitHub Desktop.
Drools family knowledge base / published by https://github.com/dacr/code-examples-manager #8a6447c0-8777-440a-8635-48f17fc14797/cd93e071bdd307c1e69a9110453b05f0fa23392c
// summary : Drools family knowledge base
// 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 : 8a6447c0-8777-440a-8635-48f17fc14797
// created-on : 2019-09-27T17:07:21+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 {
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