This commit is contained in:
Tibo De Peuter 2025-05-05 00:18:38 +02:00
parent a85169dced
commit a937b1bc44
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
15 changed files with 93 additions and 30 deletions

View file

@ -1,6 +1,7 @@
package prolog.ast.arithmetic package prolog.ast.arithmetic
import prolog.Substitutions import prolog.Substitutions
import prolog.ast.terms.Term
class Float(override val value: kotlin.Float): Number { class Float(override val value: kotlin.Float): Number {
// Floats are already evaluated // Floats are already evaluated
@ -42,4 +43,7 @@ class Float(override val value: kotlin.Float): Number {
override fun hashCode(): Int { override fun hashCode(): Int {
return super.hashCode() return super.hashCode()
} }
override fun clone(): Float = Float(value)
override fun applySubstitution(subs: Substitutions): Float = this
} }

View file

@ -3,6 +3,7 @@ package prolog.ast.arithmetic
import prolog.Answers import prolog.Answers
import prolog.Substitutions import prolog.Substitutions
import prolog.ast.logic.LogicOperand import prolog.ast.logic.LogicOperand
import prolog.ast.terms.Term
data class Integer(override val value: Int) : Number, LogicOperand() { data class Integer(override val value: Int) : Number, LogicOperand() {
// Integers are already evaluated // Integers are already evaluated
@ -41,4 +42,7 @@ data class Integer(override val value: Int) : Number, LogicOperand() {
is Integer -> Integer(value * other.value) is Integer -> Integer(value * other.value)
else -> throw IllegalArgumentException("Cannot multiply $this and $other") else -> throw IllegalArgumentException("Cannot multiply $this and $other")
} }
override fun clone(): Integer = Integer(value)
override fun applySubstitution(subs: Substitutions): Integer = this
} }

View file

@ -27,27 +27,27 @@ abstract class Clause(var head: Head, var body: Body) : Term, Resolvent {
// Only if the body can be proven, the substitutions should be returned. // Only if the body can be proven, the substitutions should be returned.
// Do this in a lazy way. // Do this in a lazy way.
// Since we are only interested in substitutions in the goal (as opposed to the head of this clause), val preHead = applySubstitution(head, subs)
// we can use variable renaming and filter out the substitutions that are not in the goal. val preGoal = applySubstitution(goal, subs)
val (end, renamed: Substitutions) = numbervars(head, Program.variableRenamingStart, subs)
val reverse = renamed.entries.associate { (a, b) -> b to a } val (headEnd, headRenaming) = numbervars(preHead, Program.variableRenamingStart, subs)
Program.variableRenamingStart = end val headReverse = headRenaming.entries.associate { (a, b) -> b to a }
Program.variableRenamingStart = headEnd
var newSubs: Substitutions = subs + renamed val renamedHead = applySubstitution(head, headRenaming)
unifyLazy(applySubstitution(goal, subs), head, newSubs).forEach { headAnswer -> unifyLazy(preGoal, renamedHead, subs).forEach { headAnswer ->
headAnswer.map { headSubs -> headAnswer.map { headSubs ->
// If the body can be proven, yield the (combined) substitutions // If the body can be proven, yield the (combined) substitutions
newSubs = subs + renamed + headSubs val preBody = applySubstitution(body, headRenaming + headSubs) as Body
body.satisfy(newSubs).forEach { bodyAnswer -> preBody.satisfy(subs).forEach { bodyAnswer ->
bodyAnswer.fold( bodyAnswer.fold(
onSuccess = { bodySubs -> onSuccess = { bodySubs ->
var result = (headSubs + bodySubs) var result = (headSubs + bodySubs)
.mapKeys { applySubstitution(it.key, reverse)} .mapKeys { applySubstitution(it.key, headReverse) }
.mapValues { applySubstitution(it.value, reverse) } .mapValues { applySubstitution(it.value, headReverse) }
result = result.map { it.key to applySubstitution(it.value, result) } result = result.map { it.key to applySubstitution(it.value, result) }
.toMap() .toMap()
.filterNot { it.key in renamed.keys && !occurs(it.key as Variable, goal, emptyMap())} .filterNot { it.key in headRenaming.keys && !occurs(it.key as Variable, goal, emptyMap())}
yield(Result.success(result)) yield(Result.success(result))
}, },
onFailure = { error -> onFailure = { error ->

View file

@ -1,6 +1,12 @@
package prolog.ast.logic package prolog.ast.logic
import prolog.Substitutions
import prolog.ast.terms.Head import prolog.ast.terms.Head
import prolog.ast.terms.Term
import prolog.builtins.True import prolog.builtins.True
import prolog.logic.applySubstitution
class Fact(head: Head) : Clause(head, True) class Fact(head: Head) : Clause(head, True) {
override fun clone(): Fact = Fact(head)
override fun applySubstitution(subs: Substitutions): Fact = Fact(applySubstitution(head as Term, subs) as Head)
}

View file

@ -1,6 +1,15 @@
package prolog.ast.logic package prolog.ast.logic
import prolog.Substitutions
import prolog.ast.terms.Body import prolog.ast.terms.Body
import prolog.ast.terms.Head import prolog.ast.terms.Head
import prolog.ast.terms.Term
import prolog.logic.applySubstitution
class Rule(head: Head, body: Body) : Clause(head, body) class Rule(head: Head, body: Body) : Clause(head, body) {
override fun clone(): Rule = Rule(head, body)
override fun applySubstitution(subs: Substitutions): Rule = Rule(
head = applySubstitution(head as Term, subs) as Head,
body = applySubstitution(body, subs) as Body
)
}

View file

@ -1,8 +1,9 @@
package prolog.ast.terms package prolog.ast.terms
import io.Logger import io.Logger
import prolog.Substitutions
class AnonymousVariable(id: Int) : Variable("_$id") { class AnonymousVariable(private val id: Int) : Variable("_$id") {
companion object { companion object {
private var counter = 0 private var counter = 0
fun create(): AnonymousVariable { fun create(): AnonymousVariable {
@ -14,4 +15,7 @@ class AnonymousVariable(id: Int) : Variable("_$id") {
} }
override fun toString(): String = "_" override fun toString(): String = "_"
override fun clone(): AnonymousVariable = AnonymousVariable(id)
override fun applySubstitution(subs: Substitutions): AnonymousVariable = this
} }

View file

@ -21,4 +21,7 @@ open class Atom(val name: String) : Goal(), Head, Body, Resolvent {
override fun hashCode(): Int { override fun hashCode(): Int {
return javaClass.hashCode() return javaClass.hashCode()
} }
override fun clone(): Atom = Atom(name)
override fun applySubstitution(subs: Substitutions): Atom = Atom(name)
} }

View file

@ -2,4 +2,4 @@ package prolog.ast.terms
import prolog.ast.logic.Satisfiable import prolog.ast.logic.Satisfiable
interface Body : Satisfiable interface Body : Term, Satisfiable

View file

@ -3,6 +3,7 @@ package prolog.ast.terms
import prolog.Answers import prolog.Answers
import prolog.Substitutions import prolog.Substitutions
import prolog.ast.logic.Resolvent import prolog.ast.logic.Resolvent
import prolog.logic.applySubstitution
import prolog.logic.unifyLazy import prolog.logic.unifyLazy
typealias Argument = Term typealias Argument = Term
@ -33,4 +34,10 @@ open class Structure(val name: Atom, var arguments: List<Argument>) : Goal(), He
override fun hashCode(): Int { override fun hashCode(): Int {
return javaClass.hashCode() return javaClass.hashCode()
} }
override fun clone(): Structure = Structure(name, arguments)
override fun applySubstitution(subs: Substitutions): Structure = Structure(
name,
arguments.map { applySubstitution(it, subs) }
)
} }

View file

@ -1,14 +1,19 @@
package prolog.ast.terms package prolog.ast.terms
import prolog.Substitutions
import prolog.logic.compare import prolog.logic.compare
import prolog.ast.arithmetic.Integer
import prolog.ast.arithmetic.Float
/** /**
* Value in Prolog. * Value in Prolog.
* *
* A [Term] is either a [Variable], [Atom], [Integer][prolog.ast.arithmetic.Integer], * A [Term] is either a [Variable], [Atom], [Integer],
* [Float][prolog.ast.arithmetic.Float] or [CompoundTerm]. * [Float] or [CompoundTerm].
* In addition, SWI-Prolog also defines the type TODO string. * In addition, SWI-Prolog also defines the type TODO string.
*/ */
interface Term : Comparable<Term> { interface Term : Comparable<Term>, Cloneable {
override fun compareTo(other: Term): Int = compare(this, other, emptyMap()) override fun compareTo(other: Term): Int = compare(this, other, emptyMap())
fun applySubstitution(subs: Substitutions): Term
public override fun clone(): Term
} }

View file

@ -39,4 +39,7 @@ open class Variable(val name: String) : Term, Body, Expression, LogicOperand() {
} }
override fun toString(): String = name override fun toString(): String = name
override fun clone(): Variable = Variable(name)
override fun applySubstitution(subs: Substitutions): Variable = this
} }

View file

@ -7,6 +7,7 @@ import prolog.ast.logic.LogicOperator
import prolog.ast.terms.Atom import prolog.ast.terms.Atom
import prolog.ast.terms.Body import prolog.ast.terms.Body
import prolog.ast.terms.Goal import prolog.ast.terms.Goal
import prolog.ast.terms.Structure
import prolog.flags.AppliedCut import prolog.flags.AppliedCut
/** /**
@ -34,6 +35,8 @@ class Cut() : Atom("!") {
override fun satisfy(subs: Substitutions): Answers { override fun satisfy(subs: Substitutions): Answers {
return sequenceOf(Result.failure(AppliedCut(emptyMap()))) return sequenceOf(Result.failure(AppliedCut(emptyMap())))
} }
override fun applySubstitution(subs: Substitutions): Cut = Cut()
} }
/** /**
@ -94,6 +97,11 @@ class Conjunction(val left: LogicOperand, private val right: LogicOperand) :
) )
} }
} }
override fun applySubstitution(subs: Substitutions): Conjunction = Conjunction(
left.applySubstitution(subs) as LogicOperand,
right.applySubstitution(subs) as LogicOperand
)
} }
/** /**
@ -105,6 +113,12 @@ open class Disjunction(private val left: LogicOperand, private val right: LogicO
yieldAll(left.satisfy(subs)) yieldAll(left.satisfy(subs))
yieldAll(right.satisfy(subs)) yieldAll(right.satisfy(subs))
} }
override fun clone(): Disjunction = Disjunction(left.clone() as LogicOperand, right.clone() as LogicOperand)
override fun applySubstitution(subs: Substitutions): Disjunction = Disjunction(
left.applySubstitution(subs) as LogicOperand,
right.applySubstitution(subs) as LogicOperand
)
} }
@Deprecated("Use Disjunction instead") @Deprecated("Use Disjunction instead")

View file

@ -42,6 +42,9 @@ class Dynamic(private val dynamicFunctor: Functor): Goal(), Body {
} }
override fun hashCode(): Int = super.hashCode() override fun hashCode(): Int = super.hashCode()
override fun clone(): Dynamic = Dynamic(dynamicFunctor)
override fun applySubstitution(subs: Substitutions): Dynamic = Dynamic(dynamicFunctor)
} }
class Assert(clause: Clause) : AssertZ(clause) { class Assert(clause: Clause) : AssertZ(clause) {

View file

@ -15,9 +15,7 @@ import prolog.ast.terms.*
// Apply substitutions to a term // Apply substitutions to a term
fun applySubstitution(term: Term, subs: Substitutions): Term = when { fun applySubstitution(term: Term, subs: Substitutions): Term = when {
term is Fact -> { term is Fact -> term.applySubstitution(subs)
Fact(applySubstitution(term.head, subs) as Head)
}
variable(term, emptyMap()) -> { variable(term, emptyMap()) -> {
val variable = term as Variable val variable = term as Variable
@ -25,8 +23,7 @@ fun applySubstitution(term: Term, subs: Substitutions): Term = when {
} }
atomic(term, subs) -> term atomic(term, subs) -> term
compound(term, subs) -> { compound(term, subs) -> {
val structure = term as Structure term.applySubstitution(subs)
Structure(structure.name, structure.arguments.map { applySubstitution(it, subs) })
} }
else -> term else -> term

View file

@ -108,8 +108,8 @@ class EvaluationTests {
val variable2 = Variable("Y") val variable2 = Variable("Y")
val parent = Rule( val parent = Rule(
Structure(Atom("parent"), listOf(variable1, variable2)), Structure(Atom("parent"), listOf(variable1, variable2)), /* :- */
/* :- */ Disjunction( Disjunction(
Structure(Atom("father"), listOf(variable1, variable2)), Structure(Atom("father"), listOf(variable1, variable2)),
/* ; */ /* ; */
Structure(Atom("mother"), listOf(variable1, variable2)) Structure(Atom("mother"), listOf(variable1, variable2))
@ -118,10 +118,14 @@ class EvaluationTests {
Program.load(listOf(father, mother, parent)) Program.load(listOf(father, mother, parent))
val result1 = Program.query(Structure(Atom("parent"), listOf(Atom("john"), Atom("jimmy")))) val result1 = Program.query(Structure(Atom("parent"), listOf(Atom("john"), Atom("jimmy")))).toList()
assertTrue(result1.toList().isNotEmpty()) assertEquals(1, result1.size, "Expected 1 result")
val result2 = Program.query(Structure(Atom("parent"), listOf(Atom("jane"), Atom("jimmy")))) assertTrue(result1[0].isSuccess, "Expected success")
assertTrue(result2.toList().isNotEmpty()) assertTrue(result1[0].getOrNull()!!.isEmpty(), "Expected no substitutions")
val result2 = Program.query(Structure(Atom("parent"), listOf(Atom("jane"), Atom("jimmy")))).toList()
assertEquals(1, result2.size, "Expected 1 result")
assertTrue(result2[0].isSuccess, "Expected success")
assertTrue(result2[0].getOrNull()!!.isEmpty(), "Expected no substitutions")
val result3 = Program.query(Structure(Atom("parent"), listOf(Atom("john"), Atom("jane")))) val result3 = Program.query(Structure(Atom("parent"), listOf(Atom("john"), Atom("jane"))))
assertFalse(result3.any()) assertFalse(result3.any())