refactor: Rework

This commit is contained in:
Tibo De Peuter 2025-04-15 12:32:59 +02:00
parent ac55ed4c64
commit 6469dd6ced
Signed by: tdpeuter
GPG key ID: 38297DE43F75FFE2
34 changed files with 593 additions and 552 deletions

View file

@ -1,17 +1,18 @@
package prolog.builtins
import prolog.Answers
import prolog.Substitutions
import prolog.ast.logic.LogicOperand
import prolog.ast.terms.Atom
import prolog.ast.terms.Body
import prolog.ast.terms.Goal
import prolog.ast.logic.LogicOperator
import prolog.logic.Substituted
/**
* Always fail.
*/
object Fail : Atom("fail"), Body {
override fun prove(subs: Substituted): Sequence<Substituted> = emptySequence()
override fun satisfy(subs: Substitutions): Answers = emptySequence()
}
/**
@ -23,7 +24,7 @@ typealias False = Fail
* Always succeed.
*/
object True : Atom("true"), Body {
override fun prove(subs: Substituted): Sequence<Substituted> = sequenceOf(emptyMap())
override fun satisfy(subs: Substitutions): Answers = sequenceOf(Result.success(emptyMap()))
}
// TODO Repeat/0
@ -34,10 +35,14 @@ object True : Atom("true"), Body {
* Conjunction (and). True if both Goal1 and Goal2 are true.
*/
class Conjunction(private val left: LogicOperand, private val right: LogicOperand) : LogicOperator(Atom(","), left, right) {
override fun prove(subs: Substituted): Sequence<Substituted> = sequence {
left.prove(subs).forEach { left ->
right.prove(subs + left).forEach { right ->
yield(left + right)
override fun satisfy(subs: Substitutions): Answers = sequence {
left.satisfy(subs).forEach { leftResult ->
leftResult.mapCatching { left ->
right.satisfy(subs + left).forEach { rightResult ->
rightResult.map { right ->
yield(Result.success(left + right))
}
}
}
}
}
@ -48,9 +53,9 @@ class Conjunction(private val left: LogicOperand, private val right: LogicOperan
*/
open class Disjunction(private val left: LogicOperand, private val right: LogicOperand) :
LogicOperator(Atom(";"), left, right) {
override fun prove(subs: Substituted): Sequence<Substituted> = sequence {
yieldAll(left.prove(subs))
yieldAll(right.prove(subs))
override fun satisfy(subs: Substitutions): Answers = sequence {
yieldAll(left.satisfy(subs))
yieldAll(right.satisfy(subs))
}
}
@ -65,12 +70,12 @@ class Bar(leftOperand: LogicOperand, rightOperand: LogicOperand) : Disjunction(l
* True if 'Goal' cannot be proven.
*/
class Not(private val goal: Goal) : LogicOperator(Atom("\\+"), rightOperand = goal) {
override fun prove(subs: Substituted): Sequence<Substituted> {
override fun satisfy(subs: Substitutions): Answers {
// If the goal can be proven, return an empty sequence
if (goal.prove(subs).toList().isNotEmpty()) {
if (goal.satisfy(subs).toList().isNotEmpty()) {
return emptySequence()
}
// If the goal cannot be proven, return a sequence with an empty map
return sequenceOf(emptyMap())
return sequenceOf(Result.success(emptyMap()))
}
}